diff options
author | upstream source tree <ports@midipix.org> | 2015-03-15 20:14:05 -0400 |
---|---|---|
committer | upstream source tree <ports@midipix.org> | 2015-03-15 20:14:05 -0400 |
commit | 554fd8c5195424bdbcabf5de30fdc183aba391bd (patch) | |
tree | 976dc5ab7fddf506dadce60ae936f43f58787092 /libjava/classpath/gnu/xml/dom/ls | |
download | cbb-gcc-4.6.4-554fd8c5195424bdbcabf5de30fdc183aba391bd.tar.bz2 cbb-gcc-4.6.4-554fd8c5195424bdbcabf5de30fdc183aba391bd.tar.xz |
obtained gcc-4.6.4.tar.bz2 from upstream website;upstream
verified gcc-4.6.4.tar.bz2.sig;
imported gcc-4.6.4 source tree from verified upstream tarball.
downloading a git-generated archive based on the 'upstream' tag
should provide you with a source tree that is binary identical
to the one extracted from the above tarball.
if you have obtained the source via the command 'git clone',
however, do note that line-endings of files in your working
directory might differ from line-endings of the respective
files in the upstream repository.
Diffstat (limited to 'libjava/classpath/gnu/xml/dom/ls')
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/DomLSException.java | 57 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/DomLSInput.java | 159 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/DomLSOutput.java | 98 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/DomLSParser.java | 567 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/DomLSSerializer.java | 353 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/FilteredSAXEventSink.java | 353 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/ReaderInputStream.java | 236 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/SAXEventSink.java | 603 | ||||
-rw-r--r-- | libjava/classpath/gnu/xml/dom/ls/WriterOutputStream.java | 97 |
9 files changed, 2523 insertions, 0 deletions
diff --git a/libjava/classpath/gnu/xml/dom/ls/DomLSException.java b/libjava/classpath/gnu/xml/dom/ls/DomLSException.java new file mode 100644 index 000000000..31efc845f --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/DomLSException.java @@ -0,0 +1,57 @@ +/* DomLSException.java -- + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import org.w3c.dom.ls.LSException; + +/** + * A DOM LS exception incorporating a cause. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class DomLSException + extends LSException +{ + + public DomLSException(short type, Exception cause) + { + super(type, (cause == null) ? null : cause.getMessage()); + initCause(cause); + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/DomLSInput.java b/libjava/classpath/gnu/xml/dom/ls/DomLSInput.java new file mode 100644 index 000000000..39b17694f --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/DomLSInput.java @@ -0,0 +1,159 @@ +/* DomLSInput.java -- + Copyright (C) 1999,2000,2001 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import gnu.java.lang.CPStringBuilder; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import org.w3c.dom.ls.LSInput; + +/** + * Specification of XML input to parse. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class DomLSInput + implements LSInput +{ + + private InputStream in; + private String systemId; + private String publicId; + private String baseURI; + private String encoding; + private boolean certifiedText; + + public Reader getCharacterStream() + { + return new InputStreamReader(in); + } + + public void setCharacterStream(Reader characterStream) + { + in = new ReaderInputStream(characterStream); + } + + public InputStream getByteStream() + { + return in; + } + + public void setByteStream(InputStream byteStream) + { + in = byteStream; + } + + public String getStringData() + { + CPStringBuilder acc = new CPStringBuilder(); + Reader reader = getCharacterStream(); + try + { + char[] buf = new char[4096]; + for (int len = reader.read(buf); len != -1; len = reader.read(buf)) + { + acc.append(buf, 0, len); + } + } + catch (IOException e) + { + return null; // ? + } + return acc.toString(); + } + + public void setStringData(String stringData) + { + in = new ReaderInputStream(new StringReader(stringData)); + } + + public String getSystemId() + { + return systemId; + } + + public void setSystemId(String systemId) + { + this.systemId = systemId; + } + + public String getPublicId() + { + return publicId; + } + + public void setPublicId(String publicId) + { + this.publicId = publicId; + } + + public String getBaseURI() + { + return baseURI; + } + + public void setBaseURI(String baseURI) + { + this.baseURI = baseURI; + } + + public String getEncoding() + { + return encoding; + } + + public void setEncoding(String encoding) + { + this.encoding = encoding; + } + + public boolean getCertifiedText() + { + return certifiedText; + } + + public void setCertifiedText(boolean certifiedText) + { + this.certifiedText = certifiedText; + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/DomLSOutput.java b/libjava/classpath/gnu/xml/dom/ls/DomLSOutput.java new file mode 100644 index 000000000..e8bec2ec1 --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/DomLSOutput.java @@ -0,0 +1,98 @@ +/* DomLSOutput.java -- + Copyright (C) 1999,2000,2001 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import org.w3c.dom.ls.LSOutput; + +/** + * Specification of XML output to produce. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class DomLSOutput + implements LSOutput +{ + + private OutputStream out; + private String systemId; + private String encoding; + + public Writer getCharacterStream() + { + return new OutputStreamWriter(out); + } + + public void setCharacterStream(Writer characterStream) + { + out = new WriterOutputStream(characterStream); + } + + public OutputStream getByteStream() + { + return out; + } + + public void setByteStream(OutputStream out) + { + this.out = out; + } + + public String getSystemId() + { + return systemId; + } + + public void setSystemId(String systemId) + { + this.systemId = systemId; + } + + public String getEncoding() + { + return encoding; + } + + public void setEncoding(String encoding) + { + this.encoding = encoding; + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/DomLSParser.java b/libjava/classpath/gnu/xml/dom/ls/DomLSParser.java new file mode 100644 index 000000000..99db79d64 --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/DomLSParser.java @@ -0,0 +1,567 @@ +/* DomLSParser.java -- + Copyright (C) 1999,2000,2001,2007 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.dom.ls; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; +import java.util.List; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import org.w3c.dom.Document; +import org.w3c.dom.DOMConfiguration; +import org.w3c.dom.DOMException; +import org.w3c.dom.DOMStringList; +import org.w3c.dom.Node; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSException; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSParserFilter; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXNotRecognizedException; +import org.xml.sax.SAXParseException; +import org.xml.sax.XMLReader; +import gnu.xml.dom.DomDocument; +import gnu.xml.dom.DomDOMException; + +/** + * Parser implementation for GNU DOM. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class DomLSParser + implements LSParser, DOMConfiguration, DOMStringList, ErrorHandler +{ + + private static final List SUPPORTED_PARAMETERS + = Arrays.asList(new String[] { "cdata-sections", + "comments", + "element-content-whitespace", + "namespaces", + "expand-entity-references", + "coalescing", + "validating", + "xinclude-aware", + "entity-resolver", + "error-handler" }); + + private LSParserFilter filter; + private final boolean async; + private String schemaType; + private SAXEventSink eventSink; + private SAXParserFactory factory; + private XMLReader reader; + + private boolean namespaceAware = true; + private boolean ignoreWhitespace; + private boolean expandEntityReferences; + private boolean ignoreComments; + private boolean coalescing; + private boolean validating; + private boolean xIncludeAware; + private EntityResolver entityResolver; + private ErrorHandler errorHandler; + + public DomLSParser(short mode, String schemaType) + throws DOMException + { + switch (mode) + { + case DOMImplementationLS.MODE_ASYNCHRONOUS: + async = true; + break; + case DOMImplementationLS.MODE_SYNCHRONOUS: + async = false; + break; + default: + throw new DomDOMException(DOMException.NOT_SUPPORTED_ERR); + } + // TODO schemaType + this.schemaType = schemaType; + factory = SAXParserFactory.newInstance(); + } + + // -- LSParser -- + + public DOMConfiguration getDomConfig() + { + return this; + } + + public LSParserFilter getFilter() + { + return filter; + } + + public void setFilter(LSParserFilter filter) + { + this.filter = filter; + } + + public boolean getAsync() + { + return async; + } + + public boolean getBusy() + { + return eventSink != null; + } + + public Document parse(LSInput input) + throws DOMException, LSException + { + if (async) + { + return doParse(input); + } + else + { + synchronized (this) + { + return doParse(input); + } + } + } + + public Document parseURI(String uri) + throws DOMException, LSException + { + LSInput input = new DomLSInput(); + input.setSystemId(uri); + return parse(input); + } + + public Node parseWithContext(LSInput input, Node context, short action) + throws DOMException, LSException + { + Document doc = (context.getNodeType() == Node.DOCUMENT_NODE) ? + (Document) context : context.getOwnerDocument(); + input.setBaseURI(doc.getDocumentURI()); + // TODO use namespaces defined on context node + Document ret = parse(input); + Node root = ret.getDocumentElement(); + root = doc.adoptNode(root); + switch (action) + { + case ACTION_APPEND_AS_CHILDREN: + context.appendChild(root); + break; + case ACTION_REPLACE_CHILDREN: + Node c1 = context.getFirstChild(); + while (c1 != null) + { + Node next = c1.getNextSibling(); + context.removeChild(c1); + c1 = next; + } + context.appendChild(root); + break; + case ACTION_INSERT_BEFORE: + Node p1 = context.getParentNode(); + p1.insertBefore(root, context); + break; + case ACTION_INSERT_AFTER: + Node p2 = context.getParentNode(); + Node r1 = context.getNextSibling(); + if (r1 == null) + { + p2.appendChild(root); + } + else + { + p2.insertBefore(root, r1); + } + break; + case ACTION_REPLACE: + Node p3 = context.getParentNode(); + Node r2 = context.getNextSibling(); + p3.removeChild(context); + if (r2 == null) + { + p3.appendChild(root); + } + else + { + p3.insertBefore(root, r2); + } + break; + } + return root; + } + + public void abort() + { + if (eventSink != null) + { + eventSink.interrupt(); + } + } + + private Document doParse(LSInput input) + throws DOMException, LSException + { + // create event sink + if (eventSink != null) + { + throw new LSException(LSException.PARSE_ERR, "parse in progress"); + } + InputSource source = getInputSource(input); + eventSink = (filter == null) ? new SAXEventSink() : + new FilteredSAXEventSink(filter); + // configure sink + eventSink.setNamespaceAware(namespaceAware); + eventSink.ignoreWhitespace = ignoreWhitespace; + eventSink.expandEntityReferences = expandEntityReferences; + eventSink.ignoreComments = ignoreComments; + eventSink.coalescing = coalescing; + // get and configure reader + XMLReader reader = getXMLReader(); + eventSink.reader = reader; + try + { + reader.setContentHandler(eventSink); + reader.setDTDHandler(eventSink); + reader.setProperty("http://xml.org/sax/properties/lexical-handler", + eventSink); + reader.setProperty("http://xml.org/sax/properties/declaration-handler", + eventSink); + reader.setFeature("http://xml.org/sax/features/namespaces", + namespaceAware); + reader.setFeature("http://xml.org/sax/features/namespace-prefixes", + true); + reader.setFeature("http://xml.org/sax/features/validation", + validating); + try + { + reader.setFeature("http://gnu.org/sax/features/coalescing", + coalescing); + } + catch (SAXNotRecognizedException e) + { + // ignore + } + try + { + reader.setFeature("http://xml.org/sax/features/use-attributes2", + true); + } + catch (SAXNotRecognizedException e) + { + // ignore + } + try + { + reader.setFeature("http://xml.org/sax/features/external-general-entities", + true); + } + catch (SAXNotRecognizedException e) + { + // ignore + } + reader.setEntityResolver(entityResolver); + reader.setErrorHandler(errorHandler); + // parse + reader.parse(source); + } + catch (DOMException e) + { + reader = null; + eventSink = null; + throw e; + } + catch (SAXException e) + { + reader = null; + eventSink = null; + throw new DomLSException(LSException.PARSE_ERR, e); + } + catch (IOException e) + { + reader = null; + eventSink = null; + throw new DomLSException(LSException.PARSE_ERR, e); + } + // return document + Document ret = eventSink.doc; + String systemId = input.getSystemId(); + if (systemId != null && ret instanceof DomDocument) + { + ((DomDocument) ret).setDocumentURI(systemId); + } + eventSink = null; + return ret; + } + + private XMLReader getXMLReader() + throws LSException + { + if (reader == null) + { + factory.setNamespaceAware(namespaceAware); + factory.setValidating(validating); + factory.setXIncludeAware(xIncludeAware); + try + { + SAXParser parser = factory.newSAXParser(); + reader = parser.getXMLReader(); + } + catch (ParserConfigurationException e) + { + throw new DomLSException(LSException.PARSE_ERR, e); + } + catch (SAXException e) + { + throw new DomLSException(LSException.PARSE_ERR, e); + } + } + return reader; + } + + private InputSource getInputSource(LSInput input) + throws LSException + { + InputSource source = null; + String systemId = input.getSystemId(); + InputStream in = input.getByteStream(); + if (in != null) + { + source = new InputSource(in); + source.setSystemId(systemId); + } + if (source == null) + { + URL url = null; + String base = input.getBaseURI(); + try + { + try + { + URL baseURL = (base == null) ? null : new URL(base); + url = (baseURL == null) ? new URL(systemId) : + new URL(baseURL, systemId); + } + catch (MalformedURLException e) + { + File baseFile = (base == null) ? null : new File(base); + url = (baseFile == null) ? new File(systemId).toURL() : + new File(baseFile, systemId).toURL(); + } + in = url.openStream(); + systemId = url.toString(); + source = new InputSource(in); + source.setSystemId(systemId); + } + catch (IOException e) + { + throw new DomLSException(LSException.PARSE_ERR, e); + } + } + return source; + } + + // -- DOMConfiguration -- + + public void setParameter(String name, Object value) + throws DOMException + { + name = name.toLowerCase(); + if ("cdata-sections".equals(name)) + { + coalescing = !((Boolean) value).booleanValue(); + } + else if ("comments".equals(name)) + { + ignoreComments = !((Boolean) value).booleanValue(); + } + else if ("element-content-whitespace".equals(name)) + { + ignoreWhitespace = !((Boolean) value).booleanValue(); + } + else if ("namespaces".equals(name)) + { + namespaceAware = ((Boolean) value).booleanValue(); + } + else if ("expand-entity-references".equals(name)) + { + expandEntityReferences = ((Boolean) value).booleanValue(); + } + else if ("coalescing".equals(name)) + { + coalescing = ((Boolean) value).booleanValue(); + } + else if ("validating".equals(name)) + { + validating = ((Boolean) value).booleanValue(); + } + else if ("xinclude-aware".equals(name)) + { + xIncludeAware = ((Boolean) value).booleanValue(); + } + else if ("entity-resolver".equals(name)) + { + entityResolver = (EntityResolver) value; + } + else if ("error-handler".equals(name)) + { + errorHandler = (ErrorHandler) value; + } + else + { + throw new DomDOMException(DOMException.NOT_SUPPORTED_ERR); + } + // invalidate reader, a new one will be created + reader = null; + } + + public Object getParameter(String name) + throws DOMException + { + name = name.toLowerCase(); + if ("cdata-sections".equals(name)) + { + return coalescing ? Boolean.FALSE : Boolean.TRUE; + } + else if ("comments".equals(name)) + { + return ignoreComments ? Boolean.FALSE : Boolean.TRUE; + } + else if ("element-content-whitespace".equals(name)) + { + return ignoreWhitespace ? Boolean.FALSE : Boolean.TRUE; + } + else if ("namespaces".equals(name)) + { + return namespaceAware ? Boolean.TRUE : Boolean.FALSE; + } + else if ("expand-entity-references".equals(name)) + { + return expandEntityReferences ? Boolean.TRUE : Boolean.FALSE; + } + else if ("coalescing".equals(name)) + { + return coalescing ? Boolean.TRUE : Boolean.FALSE; + } + else if ("validating".equals(name)) + { + return validating ? Boolean.TRUE : Boolean.FALSE; + } + else if ("xinclude-aware".equals(name)) + { + return xIncludeAware ? Boolean.TRUE : Boolean.FALSE; + } + else if ("entity-resolver".equals(name)) + { + return entityResolver; + } + else if ("error-handler".equals(name)) + { + return errorHandler; + } + else + { + throw new DomDOMException(DOMException.NOT_SUPPORTED_ERR); + } + } + + public boolean canSetParameter(String name, Object value) + { + return contains(name); + } + + public DOMStringList getParameterNames() + { + return this; + } + + // -- DOMStringList -- + + public String item(int i) + { + return (String) SUPPORTED_PARAMETERS.get(i); + } + + public int getLength() + { + return SUPPORTED_PARAMETERS.size(); + } + + public boolean contains(String str) + { + return SUPPORTED_PARAMETERS.contains(str); + } + + // -- ErrorHandler -- + + public void warning(SAXParseException e) + throws SAXException + { + if (errorHandler != null) + { + errorHandler.warning(e); + } + } + + public void error(SAXParseException e) + throws SAXException + { + if (errorHandler != null) + { + errorHandler.error(e); + } + } + + public void fatalError(SAXParseException e) + throws SAXException + { + if (errorHandler != null) + { + errorHandler.fatalError(e); + } + abort(); + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/DomLSSerializer.java b/libjava/classpath/gnu/xml/dom/ls/DomLSSerializer.java new file mode 100644 index 000000000..c282b0b9f --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/DomLSSerializer.java @@ -0,0 +1,353 @@ +/* DomLSSerializer.java -- + Copyright (C) 1999,2000,2001 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.StringWriter; +import java.io.Writer; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Arrays; +import java.util.List; +import org.w3c.dom.DOMConfiguration; +import org.w3c.dom.DOMException; +import org.w3c.dom.DOMStringList; +import org.w3c.dom.Node; +import org.w3c.dom.ls.LSException; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSSerializer; +import org.w3c.dom.ls.LSSerializerFilter; +import org.w3c.dom.traversal.NodeFilter; +import gnu.xml.dom.DomDOMException; +import gnu.xml.transform.StreamSerializer; + +/** + * Serialize a DOM node to a stream. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class DomLSSerializer + extends StreamSerializer + implements LSSerializer, DOMConfiguration, DOMStringList +{ + + private static final List SUPPORTED_PARAMETERS = + Arrays.asList(new String[] {"discard-default-content", + "xml-declaration"}); + + private LSSerializerFilter filter; + private StreamSerializer serializer; + + public DomLSSerializer() + { + super(); + discardDefaultContent = true; + } + + // -- LSSerializer -- + + public DOMConfiguration getDomConfig() + { + return this; + } + + public String getNewLine() + { + return eol; + } + + public void setNewLine(String newLine) + { + if (newLine == null) + { + newLine = System.getProperty("line.separator"); + } + eol = newLine; + } + + public LSSerializerFilter getFilter() + { + return filter; + } + + public void setFilter(LSSerializerFilter filter) + { + this.filter = filter; + } + + public boolean write(Node node, LSOutput output) + throws LSException + { + OutputStream out = output.getByteStream(); + try + { + if (out == null) + { + String systemId = output.getSystemId(); + try + { + URL url = new URL(systemId); + URLConnection connection = url.openConnection(); + connection.setDoOutput(true); + if (connection instanceof HttpURLConnection) + { + ((HttpURLConnection) connection).setRequestMethod("PUT"); + } + out = connection.getOutputStream(); + } + catch (MalformedURLException e) + { + File file = new File(systemId); + out = new FileOutputStream(file); + } + } + serialize(node, out); + out.flush(); + return true; + } + catch (IOException e) + { + throw new DomLSException(LSException.SERIALIZE_ERR, e); + } + } + + public boolean writeToURI(Node node, String uri) + throws LSException + { + LSOutput output = new DomLSOutput(); + output.setSystemId(uri); + return write(node, output); + } + + public String writeToString(Node node) + throws DOMException, LSException + { + Writer writer = new StringWriter(); + LSOutput output = new DomLSOutput(); + output.setCharacterStream(writer); + write(node, output); + return writer.toString(); + } + + public void serialize(Node node, OutputStream out) + throws IOException + { + if (filter == null) + { + super.serialize(node, out); + } + else + { + int wts = filter.getWhatToShow(); + if (wts != NodeFilter.SHOW_ALL) + { + switch (node.getNodeType()) + { + case Node.ATTRIBUTE_NODE: + if ((wts & NodeFilter.SHOW_ATTRIBUTE) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.TEXT_NODE: + if ((wts & NodeFilter.SHOW_TEXT) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.ELEMENT_NODE: + if ((wts & NodeFilter.SHOW_ELEMENT) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.CDATA_SECTION_NODE: + if ((wts & NodeFilter.SHOW_CDATA_SECTION) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.COMMENT_NODE: + if ((wts & NodeFilter.SHOW_COMMENT) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.DOCUMENT_NODE: + if ((wts & NodeFilter.SHOW_DOCUMENT) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.DOCUMENT_TYPE_NODE: + if ((wts & NodeFilter.SHOW_DOCUMENT_TYPE) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.PROCESSING_INSTRUCTION_NODE: + if ((wts & NodeFilter.SHOW_PROCESSING_INSTRUCTION) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.DOCUMENT_FRAGMENT_NODE: + if ((wts & NodeFilter.SHOW_DOCUMENT_FRAGMENT) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.ENTITY_NODE: + if ((wts & NodeFilter.SHOW_ENTITY) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.ENTITY_REFERENCE_NODE: + if ((wts & NodeFilter.SHOW_ENTITY_REFERENCE) == 0) + { + super.serialize(node, out); + return; + } + break; + case Node.NOTATION_NODE: + if ((wts & NodeFilter.SHOW_NOTATION) == 0) + { + super.serialize(node, out); + return; + } + break; + } + } + switch (filter.acceptNode(node)) + { + case NodeFilter.FILTER_ACCEPT: + super.serialize(node, out); + break; + case NodeFilter.FILTER_REJECT: + break; + case NodeFilter.FILTER_SKIP: + Node first = node.getFirstChild(); + if (first != null) + { + serialize(first, out); + } + break; + } + } + } + + // -- DOMConfiguration -- + + public void setParameter(String name, Object value) + throws DOMException + { + if ("discard-default-content".equals(name)) + { + discardDefaultContent = "true".equals(value.toString()); + } + else if ("xml-declaration".equals(name)) + { + xmlDeclaration = "false".equals(value.toString()); + } + else + { + throw new DomDOMException(DOMException.NOT_SUPPORTED_ERR); + } + } + + public Object getParameter(String name) + throws DOMException + { + if ("discard-default-content".equals(name)) + { + return discardDefaultContent ? "true" : "false"; + } + else if ("xml-declaration".equals(name)) + { + return xmlDeclaration ? "true" : "false"; + } + else + { + throw new DomDOMException(DOMException.NOT_SUPPORTED_ERR); + } + } + + public boolean canSetParameter(String name, Object value) + { + return contains(name); + } + + public DOMStringList getParameterNames() + { + return this; + } + + // -- DOMStringList -- + + public String item(int i) + { + return (String) SUPPORTED_PARAMETERS.get(i); + } + + public int getLength() + { + return SUPPORTED_PARAMETERS.size(); + } + + public boolean contains(String str) + { + return SUPPORTED_PARAMETERS.contains(str); + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/FilteredSAXEventSink.java b/libjava/classpath/gnu/xml/dom/ls/FilteredSAXEventSink.java new file mode 100644 index 000000000..65c1d37a4 --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/FilteredSAXEventSink.java @@ -0,0 +1,353 @@ +/* FilteredSAXEventSink.java -- + Copyright (C) 1999,2000,2001 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import java.util.LinkedList; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.Text; +import org.w3c.dom.ls.LSParserFilter; +import org.w3c.dom.traversal.NodeFilter; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; + +/** + * A SAX event sink that calls out to a parser filter in order to decide + * whether to insert nodes into the tree. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class FilteredSAXEventSink + extends SAXEventSink +{ + + final LSParserFilter filter; + final int whatToShow; + + /** + * Stack of elements to insert. + */ + LinkedList nodes; + + /** + * Corresponding stack of filter decisions about the nodes. + */ + LinkedList decisions; + + /** + * True when rejecting child nodes. + */ + boolean rejecting; + + FilteredSAXEventSink(LSParserFilter filter) + { + this.filter = filter; + whatToShow = filter.getWhatToShow(); + } + + public void startDocument() + throws SAXException + { + if (interrupted) + { + return; + } + nodes = new LinkedList(); + decisions = new LinkedList(); + + super.startDocument(); + } + + public void endDocument() + throws SAXException + { + if (interrupted) + { + return; + } + super.endDocument(); + + switch (getDecision(ctx, false)) + { + case LSParserFilter.FILTER_REJECT: + ctx = null; + doc = null; + break; + } + + nodes = null; + decisions = null; + } + + public void startElement(String uri, String localName, String qName, + Attributes atts) + throws SAXException + { + if (rejecting || interrupted) + { + return; + } + Element element = createElement(uri, localName, qName, atts); + ctx = element; + + short decision = getDecision(element, true); + nodes.addLast(element); + decisions.addLast(new Short(decision)); + + switch (decision) + { + case LSParserFilter.FILTER_REJECT: + rejecting = true; + break; + case LSParserFilter.FILTER_INTERRUPT: + interrupted = true; + break; + } + } + + protected Attr createAttr(Attributes atts, int index) + { + Attr attr = super.createAttr(atts, index); + short decision = getDecision(attr, false); + switch (decision) + { + case LSParserFilter.FILTER_REJECT: + return null; + case LSParserFilter.FILTER_INTERRUPT: + interrupted = true; + return null; + } + return attr; + } + + public void endElement(String uri, String localName, String qName) + throws SAXException + { + if (rejecting || interrupted) + { + return; + } + super.endElement(uri, localName, qName); + + Element element = (Element) nodes.removeLast(); + Node parent = nodes.isEmpty() ? doc : (Node) nodes.getLast(); + ctx = parent; + short decision = ((Short) decisions.removeLast()).shortValue(); + switch (decision) + { + case LSParserFilter.FILTER_SKIP: + // Add all children of element to parent + for (Node child = element.getFirstChild(); child != null; + child = child.getNextSibling()) + { + parent.insertBefore(child, element); + } + return; + case LSParserFilter.FILTER_REJECT: + rejecting = false; + break; + } + decision = getDecision(element, false); + switch (decision) + { + case LSParserFilter.FILTER_ACCEPT: + parent.appendChild(element); + break; + case LSParserFilter.FILTER_INTERRUPT: + interrupted = true; + break; + } + } + + public void characters(char[] c, int off, int len) + throws SAXException + { + if (rejecting || interrupted) + { + return; + } + Text text = createText(c, off, len); + short decision = getDecision(text, false); + switch (decision) + { + case LSParserFilter.FILTER_ACCEPT: + ctx.appendChild(text); + break; + case LSParserFilter.FILTER_INTERRUPT: + interrupted = true; + break; + } + } + + public void processingInstruction(String target, String data) + throws SAXException + { + if (rejecting || interrupted || inDTD) + { + return; + } + Node pi = createProcessingInstruction(target, data); + short decision = getDecision(pi, false); + switch (decision) + { + case LSParserFilter.FILTER_ACCEPT: + ctx.appendChild(pi); + break; + case LSParserFilter.FILTER_INTERRUPT: + interrupted = true; + break; + } + } + + public void startDTD(String name, String publicId, String systemId) + throws SAXException + { + if (interrupted) + { + return; + } + Node doctype = createDocumentType(name, publicId, systemId); + ctx = doctype; + inDTD = true; + nodes.addLast(doctype); + decisions.addLast(new Short(LSParserFilter.FILTER_ACCEPT)); + } + + public void endDTD() + throws SAXException + { + if (interrupted) + { + return; + } + Node doctype = (Node) nodes.removeLast(); + decisions.removeLast(); + inDTD = false; + ctx = doc; + short decision = getDecision(doctype, false); + switch (decision) + { + case LSParserFilter.FILTER_ACCEPT: + ctx.appendChild(doctype); + break; + case LSParserFilter.FILTER_INTERRUPT: + interrupted = true; + break; + } + } + + public void comment(char[] c, int off, int len) + throws SAXException + { + if (rejecting || interrupted || inDTD) + { + return; + } + Node comment = createComment(c, off, len); + short decision = getDecision(comment, false); + switch (decision) + { + case LSParserFilter.FILTER_ACCEPT: + ctx.appendChild(comment); + break; + case LSParserFilter.FILTER_INTERRUPT: + interrupted = true; + break; + } + } + + // TODO declarations + + short getDecision(Node node, boolean start) + { + boolean show = (whatToShow == NodeFilter.SHOW_ALL); + if (!show) + { + switch (node.getNodeType()) + { + case Node.ATTRIBUTE_NODE: + show = ((whatToShow & NodeFilter.SHOW_ATTRIBUTE) != 0); + break; + case Node.TEXT_NODE: + show = ((whatToShow & NodeFilter.SHOW_TEXT) != 0); + break; + case Node.CDATA_SECTION_NODE: + show = ((whatToShow & NodeFilter.SHOW_CDATA_SECTION) != 0); + break; + case Node.ELEMENT_NODE: + show = ((whatToShow & NodeFilter.SHOW_ELEMENT) != 0); + break; + case Node.COMMENT_NODE: + show = ((whatToShow & NodeFilter.SHOW_COMMENT) != 0); + break; + case Node.DOCUMENT_NODE: + show = ((whatToShow & NodeFilter.SHOW_DOCUMENT) != 0); + break; + case Node.PROCESSING_INSTRUCTION_NODE: + show = ((whatToShow & NodeFilter.SHOW_PROCESSING_INSTRUCTION) != 0); + break; + case Node.DOCUMENT_FRAGMENT_NODE: + show = ((whatToShow & NodeFilter.SHOW_DOCUMENT_FRAGMENT) != 0); + break; + case Node.DOCUMENT_TYPE_NODE: + show = ((whatToShow & NodeFilter.SHOW_DOCUMENT_TYPE) != 0); + break; + case Node.ENTITY_REFERENCE_NODE: + show = ((whatToShow & NodeFilter.SHOW_ENTITY_REFERENCE) != 0); + break; + case Node.ENTITY_NODE: + show = ((whatToShow & NodeFilter.SHOW_ENTITY) != 0); + break; + case Node.NOTATION_NODE: + show = ((whatToShow & NodeFilter.SHOW_NOTATION) != 0); + break; + } + } + if (!show) + { + return LSParserFilter.FILTER_ACCEPT; + } + if (start) + { + return filter.startElement((Element) node); + } + return filter.acceptNode(node); + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/ReaderInputStream.java b/libjava/classpath/gnu/xml/dom/ls/ReaderInputStream.java new file mode 100644 index 000000000..cf279ab39 --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/ReaderInputStream.java @@ -0,0 +1,236 @@ +/* ReaderInputStream.java -- + Copyright (C) 1999, 2000, 2001, 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import java.io.InputStream; +import java.io.IOException; +import java.io.Reader; + +/** + * Character stream wrapper. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + * @author <a href='mailto:mark@klomp.org'>Mark Wielaard</a> + */ +public class ReaderInputStream + extends InputStream +{ + + private Reader reader; + private String encoding; + + // Holds extra spillover data if necessary + private byte extra[]; + private int pos; + + private byte extra_marked[]; + private int pos_marked; + + public ReaderInputStream(Reader reader) + { + this.reader = reader; + this.encoding = "UTF-8"; + } + + void setEncoding(String encoding) + { + this.encoding = encoding; + } + + public int read() + throws IOException + { + if (extra != null) + { + int result = extra[pos]; + pos++; + if (pos >= extra.length) + { + extra = null; + } + return result; + } + return reader.read(); + } + + public int read(byte[] b) + throws IOException + { + return read(b, 0, b.length); + } + + public int read(byte[] b, int off, int len) + throws IOException + { + if (len == 0) + { + return 0; + } + + if (extra != null) + { + int available = extra.length - pos; + int l = available < len ? available : len; + System.arraycopy(extra, 0, b, off, l); + pos += l; + if (pos >= extra.length) + { + extra = null; + } + return l; + } + + char[] c = new char[len]; + int l = reader.read(c, 0, len); + if (l == -1) + { + return -1; + } + + String s = new String(c, 0, l); + byte[] d = s.getBytes(encoding); + + int available = d.length; + int more = d.length - len; + if (more > 0) + { + extra = new byte[more]; + pos = 0; + System.arraycopy(d, len, extra, 0, more); + available -= more; + } + + System.arraycopy(d, 0, b, off, available); + return available; + } + + public void close() + throws IOException + { + reader.close(); + } + + public boolean markSupported() + { + return reader.markSupported(); + } + + public void mark(int limit) + { + if (extra != null) + { + extra_marked = new byte[extra.length]; + System.arraycopy(extra, 0, extra_marked, 0, extra.length); + pos_marked = pos; + } + else + { + extra_marked = null; + } + + try + { + // Note that this might be a bit more than asked for. + // Because we might also have the extra_marked bytes. + // That is fine (and necessary for reset() to work). + reader.mark(limit); + } + catch (IOException ioe) + { + throw new RuntimeException(ioe); + } + } + + public void reset() + throws IOException + { + extra = extra_marked; + pos = pos_marked; + extra_marked = null; + + reader.reset(); + } + + public long skip(long n) + throws IOException + { + long done = 0; + if (extra != null) + { + int available = extra.length - pos; + done = available < n ? available : n; + pos += done; + if (pos >= extra.length) + { + extra = null; + } + } + + n -= done; + if (n > 0) + { + return reader.skip(n) + done; + } + else + { + return done; + } + } + + /** + * Returns conservative number of bytes available without blocking. + * Actual number of bytes that can be read without blocking might + * be (much) bigger. + */ + public int available() + throws IOException + { + if (extra != null) + { + return pos - extra.length; + } + + return reader.ready() ? 1 : 0; + } + + public String toString() + { + return getClass().getName() + "[" + reader + ", " + encoding + "]"; + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/SAXEventSink.java b/libjava/classpath/gnu/xml/dom/ls/SAXEventSink.java new file mode 100644 index 000000000..06333dd7e --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/SAXEventSink.java @@ -0,0 +1,603 @@ +/* SAXEventSink.java -- + Copyright (C) 1999,2000,2001 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import javax.xml.XMLConstants; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentType; +import org.w3c.dom.Element; +import org.w3c.dom.Entity; +import org.w3c.dom.EntityReference; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.Text; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.DTDHandler; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.SAXNotRecognizedException; +import org.xml.sax.SAXNotSupportedException; +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 gnu.xml.dom.DomAttr; +import gnu.xml.dom.DomDocument; +import gnu.xml.dom.DomDoctype; +import gnu.xml.dom.DomNode; + +/** + * A SAX content and lexical handler used to construct a DOM document. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class SAXEventSink + implements ContentHandler, LexicalHandler, DTDHandler, DeclHandler +{ + + private static final String XMLNS_URI = XMLConstants.XMLNS_ATTRIBUTE_NS_URI; + private static final String XMLNS_PREFIX = XMLConstants.XMLNS_ATTRIBUTE; + private static final HashSet PREDEFINED_ENTITIES = new HashSet(); + static + { + PREDEFINED_ENTITIES.add("amp"); + PREDEFINED_ENTITIES.add("lt"); + PREDEFINED_ENTITIES.add("gt"); + PREDEFINED_ENTITIES.add("quot"); + PREDEFINED_ENTITIES.add("apos"); + } + + private boolean namespaceAware; + boolean ignoreWhitespace; + boolean expandEntityReferences; + boolean ignoreComments; + boolean coalescing; + + XMLReader reader; // reference back to the parser to get features + + DomDocument doc; // document being constructed + Node ctx; // current context (parent node) + LinkedList entityCtx; // entity context + List pending; // namespace nodes waiting for a declaring element + Locator locator; + boolean inCDATA; + boolean inDTD; + boolean interrupted; + + void interrupt() + { + interrupted = true; + } + + public Document getDocument() + { + return doc; + } + + public void setReader(XMLReader reader) + { + this.reader = reader; + } + + // -- ContentHandler2 -- + + public void setDocumentLocator(Locator locator) + { + this.locator = locator; + } + + public void setNamespaceAware(boolean namespaceAware) + { + this.namespaceAware = namespaceAware; + } + + public void startDocument() + throws SAXException + { + if (namespaceAware) + { + pending = new LinkedList(); + } + doc = new DomDocument(); + doc.setStrictErrorChecking(false); + doc.setBuilding(true); + doc.setDefaultAttributes(false); + ctx = doc; + + final String FEATURES = "http://xml.org/sax/features/"; + final String PROPERTIES = "http://xml.org/sax/properties/"; + final String GNU_PROPERTIES = "http://gnu.org/sax/properties/"; + + if (reader != null) + { + boolean standalone = reader.getFeature(FEATURES + "is-standalone"); + doc.setXmlStandalone(standalone); + try + { + String version = (String) reader.getProperty(PROPERTIES + + "document-xml-version"); + doc.setXmlVersion(version); + } + catch (SAXNotRecognizedException e) + { + } + catch (SAXNotSupportedException e) + { + } + try + { + String encoding = (String) reader.getProperty(GNU_PROPERTIES + + "document-xml-encoding"); + doc.setXmlEncoding(encoding); + } + catch (SAXNotRecognizedException e) + { + } + catch (SAXNotSupportedException e) + { + } + } + if (locator != null && locator instanceof Locator2) + { + String encoding = ((Locator2) locator).getEncoding(); + doc.setInputEncoding(encoding); + } + } + + public void endDocument() + throws SAXException + { + doc.setStrictErrorChecking(true); + doc.setBuilding(false); + doc.setDefaultAttributes(true); + DomDoctype doctype = (DomDoctype) doc.getDoctype(); + if (doctype != null) + { + doctype.makeReadonly(); + } + ctx = null; + locator = null; + } + + public void startPrefixMapping(String prefix, String uri) + throws SAXException + { + if (namespaceAware) + { + String nsName = (prefix != null && prefix.length() > 0) ? + XMLNS_PREFIX + ":" + prefix : XMLNS_PREFIX; + DomAttr ns = (DomAttr) doc.createAttributeNS(XMLNS_URI, nsName); + ns.setNodeValue(uri); + if (ctx.getNodeType() == Node.ATTRIBUTE_NODE) + { + // Add to owner element + Node target = ((Attr) ctx).getOwnerElement(); + target.getAttributes().setNamedItemNS(ns); + } + else + { + // Add to pending list; namespace node will be inserted when + // element is seen + pending.add(ns); + } + } + } + + public void endPrefixMapping(String prefix) + throws SAXException + { + } + + public void startElement(String uri, String localName, String qName, + Attributes atts) + throws SAXException + { + if (interrupted) + { + return; + } + Element element = createElement(uri, localName, qName, atts); + // add element to context + ctx.appendChild(element); + ctx = element; + } + + protected Element createElement(String uri, String localName, String qName, + Attributes atts) + throws SAXException + { + // create element node + Element element = namespaceAware ? + doc.createElementNS(uri, qName) : + doc.createElement(qName); + NamedNodeMap attrs = element.getAttributes(); + if (namespaceAware && !pending.isEmpty()) + { + // add pending namespace nodes + for (Iterator i = pending.iterator(); i.hasNext(); ) + { + Node ns = (Node) i.next(); + attrs.setNamedItemNS(ns); + } + pending.clear(); + } + // add attributes + int len = atts.getLength(); + for (int i = 0; i < len; i++) + { + // create attribute + Attr attr = createAttr(atts, i); + if (attr != null) + { + // add attribute to element + if (namespaceAware) + { + attrs.setNamedItemNS(attr); + } + else + { + attrs.setNamedItem(attr); + } + } + } + return element; + } + + protected Attr createAttr(Attributes atts, int index) + { + DomAttr attr; + if (namespaceAware) + { + String a_uri = atts.getURI(index); + String a_qName = atts.getQName(index); + attr = (DomAttr) doc.createAttributeNS(a_uri, a_qName); + } + else + { + String a_qName = atts.getQName(index); + attr = (DomAttr) doc.createAttribute(a_qName); + } + attr.setNodeValue(atts.getValue(index)); + if (atts instanceof Attributes2) + { + Attributes2 atts2 = (Attributes2) atts; + // TODO attr.setDeclared(atts2.isDeclared(index)); + attr.setSpecified(atts2.isSpecified(index)); + } + return attr; + } + + public void endElement(String uri, String localName, String qName) + throws SAXException + { + if (interrupted) + { + return; + } + if (namespaceAware) + { + pending.clear(); + } + ctx = ctx.getParentNode(); + } + + public void characters(char[] c, int off, int len) + throws SAXException + { + if (interrupted || len < 1) + { + return; + } + ctx.appendChild(createText(c, off, len)); + } + + protected Text createText(char[] c, int off, int len) + throws SAXException + { + Text text = (inCDATA && !coalescing) ? + doc.createCDATASection(new String(c, off, len)) : + doc.createTextNode(new String(c, off, len)); + return text; + } + + public void ignorableWhitespace(char[] c, int off, int len) + throws SAXException + { + if (interrupted) + { + return; + } + if (!ignoreWhitespace) + { + characters(c, off, len); + } + } + + public void processingInstruction(String target, String data) + throws SAXException + { + if (interrupted) + { + return; + } + Node pi = createProcessingInstruction(target, data); + ctx.appendChild(pi); + } + + protected Node createProcessingInstruction(String target, String data) + { + return doc.createProcessingInstruction(target, data); + } + + public void skippedEntity(String name) + throws SAXException + { + // This callback is totally pointless + } + + // -- LexicalHandler -- + + public void startDTD(String name, String publicId, String systemId) + throws SAXException + { + if (interrupted) + { + return; + } + Node doctype = createDocumentType(name, publicId, systemId); + doc.appendChild(doctype); + ctx = doctype; + inDTD = true; + } + + protected Node createDocumentType(String name, String publicId, + String systemId) + { + return new DomDoctype(doc, name, publicId, systemId); + } + + public void endDTD() + throws SAXException + { + if (interrupted) + { + return; + } + inDTD = false; + ctx = ctx.getParentNode(); + } + + public void startEntity(String name) + throws SAXException + { + if (interrupted) + return; + DocumentType doctype = doc.getDoctype(); + if (doctype == null) + { + throw new SAXException("SAX parser error: " + + "reference to entity in undeclared doctype"); + } + if ("[dtd]".equals(name) || name.charAt(0) == '%') + return; + if (PREDEFINED_ENTITIES.contains(name)) + return; + // Get entity + NamedNodeMap entities = doctype.getEntities(); + Entity entity = (Entity) entities.getNamedItem(name); + if (entity == null) + { + throw new SAXException("SAX parser error: " + + "reference to undeclared entity: " + name); + } + EntityReference ref = doc.createEntityReference(name); + // DomDocument populates with the entity replacement text, remove this + Node child = ref.getFirstChild(); + while (child != null) + { + Node nextChild = child.getNextSibling(); + ref.removeChild(child); + child = nextChild; + } + ctx.appendChild(ref); + ctx = ref; + } + + public void endEntity(String name) + throws SAXException + { + if (interrupted) + return; + if ("[dtd]".equals(name) || name.charAt(0) == '%') + return; + if (PREDEFINED_ENTITIES.contains(name)) + return; + // Get entity reference + EntityReference ref = (EntityReference) ctx; + if (!ref.getNodeName().equals(name)) + throw new SAXException("expecting end of "+ref.getNodeName()+" entity"); + ctx = ctx.getParentNode(); + if (ref instanceof DomNode) + ((DomNode) ref).makeReadonly(); + if (expandEntityReferences) + { + // Move entity content from reference node onto context + Node child = ref.getFirstChild(); + while (child != null) + { + Node nextChild = child.getNextSibling(); + ctx.appendChild(child); + child = nextChild; + } + ctx.removeChild(ref); + } + } + + public void startCDATA() + throws SAXException + { + inCDATA = true; + } + + public void endCDATA() + throws SAXException + { + inCDATA = false; + } + + public void comment(char[] c, int off, int len) + throws SAXException + { + if (interrupted) + { + return; + } + Node comment = createComment(c, off, len); + ctx.appendChild(comment); + } + + protected Node createComment(char[] c, int off, int len) + { + return doc.createComment(new String(c, off, len)); + } + + // -- DTDHandler -- + + public void notationDecl(String name, String publicId, String systemId) + throws SAXException + { + if (interrupted) + { + return; + } + if (!inDTD) + throw new SAXException("notation decl outside DTD"); + DomDoctype doctype = (DomDoctype) ctx; + doctype.declareNotation(name, publicId, systemId); + } + + public void unparsedEntityDecl(String name, String publicId, String systemId, + String notationName) + throws SAXException + { + if (interrupted) + { + return; + } + if (!inDTD) + throw new SAXException("unparsed entity decl outside DTD"); + DomDoctype doctype = (DomDoctype) ctx; + Entity entity = doctype.declareEntity(name, publicId, systemId, + notationName); + } + + // -- DeclHandler -- + + public void elementDecl(String name, String model) + throws SAXException + { + if (interrupted) + { + return; + } + if (!inDTD) + throw new SAXException("element decl outside DTD"); + // Ignore fake element declarations generated by ValidationConsumer. + // If an element is not really declared in the DTD it will not be + // declared in the document model. + if (!(ctx instanceof DomDoctype)) + { + return; + } + DomDoctype doctype = (DomDoctype) ctx; + doctype.elementDecl(name, model); + } + + public void attributeDecl(String eName, String aName, String type, + String mode, String value) + throws SAXException + { + if (interrupted) + { + return; + } + if (!inDTD) + throw new SAXException("attribute decl outside DTD"); + DomDoctype doctype = (DomDoctype) ctx; + doctype.attributeDecl(eName, aName, type, mode, value); + } + + public void internalEntityDecl(String name, String value) + throws SAXException + { + if (interrupted) + { + return; + } + if (!inDTD) + throw new SAXException("internal entity decl outside DTD"); + DomDoctype doctype = (DomDoctype) ctx; + Entity entity = doctype.declareEntity(name, null, null, null); + if (entity != null) + { + Node text = doc.createTextNode(value); + entity.appendChild(text); + } + } + + public void externalEntityDecl(String name, String publicId, String systemId) + throws SAXException + { + if (interrupted) + { + return; + } + if (!inDTD) + throw new SAXException("external entity decl outside DTD"); + DomDoctype doctype = (DomDoctype) ctx; + Entity entity = doctype.declareEntity(name, publicId, systemId, null); + } + +} diff --git a/libjava/classpath/gnu/xml/dom/ls/WriterOutputStream.java b/libjava/classpath/gnu/xml/dom/ls/WriterOutputStream.java new file mode 100644 index 000000000..f1ae344f4 --- /dev/null +++ b/libjava/classpath/gnu/xml/dom/ls/WriterOutputStream.java @@ -0,0 +1,97 @@ +/* WriterOutputStream.java -- + Copyright (C) 1999,2000,2001 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.dom.ls; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; + +/** + * Character stream wrapper. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class WriterOutputStream + extends OutputStream +{ + + private Writer writer; + private String encoding; + + public WriterOutputStream(Writer writer) + { + this.writer = writer; + this.encoding = "UTF-8"; + } + + void setEncoding(String encoding) + { + this.encoding = encoding; + } + + public void write(int c) + throws IOException + { + writer.write(c); + } + + public void write(byte[] b) + throws IOException + { + write(b, 0, b.length); + } + + public void write(byte[] b, int off, int len) + throws IOException + { + writer.write(new String(b, off, len, encoding)); + } + + public void close() + throws IOException + { + writer.close(); + } + + public void flush() + throws IOException + { + writer.flush(); + } + +} |