You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@santuario.apache.org by co...@apache.org on 2018/11/23 13:30:10 UTC
svn commit: r1847262 [1/2] - in
/santuario/xml-security-java/branches/staxutils/src:
main/java/org/apache/xml/security/c14n/
main/java/org/apache/xml/security/c14n/implementations/
main/java/org/apache/xml/security/encryption/ main/java/org/apache/xml/...
Author: coheigea
Date: Fri Nov 23 13:30:09 2018
New Revision: 1847262
URL: http://svn.apache.org/viewvc?rev=1847262&view=rev
Log:
Switching to use CXF's StaxUtils for DOM parsing. Still having problems with DTD parsing.
Added:
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/AbstractDOMStreamReader.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DOMUtils.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthExceededStaxException.java
- copied, changed from r1847258, santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthRestrictingStreamReader.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthXMLStreamReader.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DocumentDepthProperties.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/FastStack.java
- copied, changed from r1847258, santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/StaxUtils.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/SystemPropertyAction.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/W3CDOMStreamReader.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/W3CNamespaceContext.java
Modified:
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/Canonicalizer.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/CanonicalizerSpi.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315Excl.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/CanonicalizerBase.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/KeyResolverSpi.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/implementations/RetrievalMethodResolver.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/Manifest.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/SignedInfo.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/XMLSignatureInput.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/transforms/implementations/TransformBase64Decode.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/transforms/implementations/TransformXPath2Filter.java
santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/utils/XMLUtils.java
santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java
santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/c14n/implementations/Canonicalizer11Test.java
santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/c14n/implementations/Canonicalizer20010315Test.java
santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/interop/InteropTestBase.java
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/Canonicalizer.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/Canonicalizer.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/Canonicalizer.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/Canonicalizer.java Fri Nov 23 13:30:09 2018
@@ -26,6 +26,8 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
+import javax.xml.stream.XMLStreamException;
+
import org.apache.xml.security.c14n.implementations.Canonicalizer11_OmitComments;
import org.apache.xml.security.c14n.implementations.Canonicalizer11_WithComments;
import org.apache.xml.security.c14n.implementations.Canonicalizer20010315ExclOmitComments;
@@ -246,10 +248,11 @@ public class Canonicalizer {
* @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws org.xml.sax.SAXException
+ * @throws XMLStreamException
*/
public byte[] canonicalize(byte[] inputBytes)
throws javax.xml.parsers.ParserConfigurationException,
- java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
+ java.io.IOException, org.xml.sax.SAXException, CanonicalizationException, XMLStreamException {
Document document = null;
try (InputStream bais = new ByteArrayInputStream(inputBytes)) {
InputSource in = new InputSource(bais);
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/CanonicalizerSpi.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/CanonicalizerSpi.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/CanonicalizerSpi.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/CanonicalizerSpi.java Fri Nov 23 13:30:09 2018
@@ -22,6 +22,8 @@ import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.util.Set;
+import javax.xml.stream.XMLStreamException;
+
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@@ -48,10 +50,11 @@ public abstract class CanonicalizerSpi {
* @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws org.xml.sax.SAXException
+ * @throws XMLStreamException
*/
public byte[] engineCanonicalize(byte[] inputBytes)
throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
- org.xml.sax.SAXException, CanonicalizationException {
+ org.xml.sax.SAXException, CanonicalizationException, XMLStreamException {
Document document = null;
try (java.io.InputStream bais = new ByteArrayInputStream(inputBytes)) {
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315.java Fri Nov 23 13:30:09 2018
@@ -26,6 +26,7 @@ import java.util.SortedSet;
import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.helper.C14nHelper;
@@ -296,7 +297,7 @@ public abstract class Canonicalizer20010
}
protected void circumventBugIfNeeded(XMLSignatureInput input)
- throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
+ throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, XMLStreamException {
if (!input.isNeedsToBeExpanded()) {
return;
}
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315Excl.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315Excl.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315Excl.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/Canonicalizer20010315Excl.java Fri Nov 23 13:30:09 2018
@@ -25,6 +25,7 @@ import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.helper.C14nHelper;
@@ -337,7 +338,7 @@ public abstract class Canonicalizer20010
protected void circumventBugIfNeeded(XMLSignatureInput input)
throws CanonicalizationException, ParserConfigurationException,
- IOException, SAXException {
+ IOException, SAXException, XMLStreamException {
if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty()) {
return;
}
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/CanonicalizerBase.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/CanonicalizerBase.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/CanonicalizerBase.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/c14n/implementations/CanonicalizerBase.java Fri Nov 23 13:30:09 2018
@@ -31,6 +31,7 @@ import java.util.Map;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.CanonicalizerSpi;
@@ -160,11 +161,7 @@ public abstract class CanonicalizerBase
}
}
return null;
- } catch (ParserConfigurationException ex) {
- throw new CanonicalizationException(ex);
- } catch (IOException ex) {
- throw new CanonicalizationException(ex);
- } catch (SAXException ex) {
+ } catch (ParserConfigurationException | IOException | SAXException | XMLStreamException ex) {
throw new CanonicalizationException(ex);
}
}
@@ -654,7 +651,7 @@ public abstract class CanonicalizerBase
throws CanonicalizationException, DOMException, IOException;
abstract void circumventBugIfNeeded(XMLSignatureInput input)
- throws CanonicalizationException, ParserConfigurationException, IOException, SAXException;
+ throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, XMLStreamException;
/**
* Outputs an Attribute to the internal Writer.
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java Fri Nov 23 13:30:09 2018
@@ -24,6 +24,7 @@ import java.io.InputStream;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;
@@ -89,12 +90,8 @@ public class DocumentSerializer extends
child = fragElt.getFirstChild();
}
return result;
- } catch (SAXException se) {
- throw new XMLEncryptionException(se);
- } catch (ParserConfigurationException pce) {
- throw new XMLEncryptionException(pce);
- } catch (IOException ioe) {
- throw new XMLEncryptionException(ioe);
+ } catch (ParserConfigurationException | IOException | SAXException | XMLStreamException ex) {
+ throw new XMLEncryptionException(ex);
}
}
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/KeyResolverSpi.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/KeyResolverSpi.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/KeyResolverSpi.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/KeyResolverSpi.java Fri Nov 23 13:30:09 2018
@@ -28,6 +28,7 @@ import java.util.HashMap;
import javax.crypto.SecretKey;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.keys.storage.StorageResolver;
import org.apache.xml.security.utils.XMLUtils;
@@ -273,11 +274,7 @@ public abstract class KeyResolverSpi {
try (InputStream is = new ByteArrayInputStream(bytes)) {
Document doc = XMLUtils.read(is, secureValidation);
return doc.getDocumentElement();
- } catch (SAXException ex) {
- throw new KeyResolverException(ex);
- } catch (IOException ex) {
- throw new KeyResolverException(ex);
- } catch (ParserConfigurationException ex) {
+ } catch (ParserConfigurationException | IOException | SAXException | XMLStreamException ex) {
throw new KeyResolverException(ex);
}
}
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/implementations/RetrievalMethodResolver.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/implementations/RetrievalMethodResolver.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/implementations/RetrievalMethodResolver.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/keys/keyresolver/implementations/RetrievalMethodResolver.java Fri Nov 23 13:30:09 2018
@@ -32,6 +32,7 @@ import java.util.ListIterator;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.exceptions.XMLSecurityException;
@@ -126,7 +127,9 @@ public class RetrievalMethodResolver ext
LOG.debug("ParserConfigurationException", e);
} catch (SAXException e) {
LOG.debug("SAXException", e);
- }
+ } catch (XMLStreamException e) {
+ LOG.debug("XMLStreamException", e);
+ }
return null;
}
@@ -184,6 +187,8 @@ public class RetrievalMethodResolver ext
LOG.debug("ParserConfigurationException", e);
} catch (SAXException e) {
LOG.debug("SAXException", e);
+ } catch (XMLStreamException e) {
+ LOG.debug("XMLStreamException", e);
}
return null;
}
@@ -234,7 +239,7 @@ public class RetrievalMethodResolver ext
private static Element obtainReferenceElement(XMLSignatureInput resource, boolean secureValidation)
throws CanonicalizationException, ParserConfigurationException,
- IOException, SAXException, KeyResolverException {
+ IOException, SAXException, KeyResolverException, XMLStreamException {
Element e;
if (resource.isElement()){
e = (Element) resource.getSubNode();
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/Manifest.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/Manifest.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/Manifest.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/Manifest.java Fri Nov 23 13:30:09 2018
@@ -30,6 +30,7 @@ import java.util.Map;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
@@ -399,11 +400,7 @@ public class Manifest extends SignatureE
}
manifestReferences = referencedManifest.getVerificationResults();
- } catch (IOException ex) {
- throw new ReferenceNotInitializedException(ex);
- } catch (ParserConfigurationException ex) {
- throw new ReferenceNotInitializedException(ex);
- } catch (SAXException ex) {
+ } catch (ParserConfigurationException | IOException | SAXException | XMLStreamException ex) {
throw new ReferenceNotInitializedException(ex);
}
}
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/SignedInfo.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/SignedInfo.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/SignedInfo.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/SignedInfo.java Fri Nov 23 13:30:09 2018
@@ -26,6 +26,7 @@ import java.io.OutputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.algorithms.SignatureAlgorithm;
import org.apache.xml.security.c14n.CanonicalizationException;
@@ -218,11 +219,7 @@ public class SignedInfo extends Manifest
element.getParentNode().replaceChild(imported, element);
return (Element) imported;
}
- } catch (ParserConfigurationException ex) {
- throw new XMLSecurityException(ex);
- } catch (IOException ex) {
- throw new XMLSecurityException(ex);
- } catch (SAXException ex) {
+ } catch (ParserConfigurationException | IOException | SAXException | XMLStreamException ex) {
throw new XMLSecurityException(ex);
}
}
Modified: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/XMLSignatureInput.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/XMLSignatureInput.java?rev=1847262&r1=1847261&r2=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/XMLSignatureInput.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/signature/XMLSignatureInput.java Fri Nov 23 13:30:09 2018
@@ -30,6 +30,7 @@ import java.util.List;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.implementations.Canonicalizer11_OmitComments;
@@ -191,9 +192,10 @@ public class XMLSignatureInput {
* @throws IOException
* @throws ParserConfigurationException
* @throws CanonicalizationException
+ * @throws XMLStreamException
*/
public Set<Node> getNodeSet() throws CanonicalizationException, ParserConfigurationException,
- IOException, SAXException {
+ IOException, SAXException, XMLStreamException {
return getNodeSet(false);
}
@@ -215,9 +217,10 @@ public class XMLSignatureInput {
* @throws IOException
* @throws ParserConfigurationException
* @throws CanonicalizationException
+ * @throws XMLStreamException
*/
public Set<Node> getNodeSet(boolean circumvent) throws ParserConfigurationException,
- IOException, SAXException, CanonicalizationException {
+ IOException, SAXException, CanonicalizationException, XMLStreamException {
if (inputNodeSet != null) {
return inputNodeSet;
}
@@ -568,7 +571,7 @@ public class XMLSignatureInput {
}
void convertToNodes() throws CanonicalizationException,
- ParserConfigurationException, IOException, SAXException {
+ ParserConfigurationException, IOException, SAXException, XMLStreamException {
// select all nodes, also the comments.
try {
Document doc = XMLUtils.read(this.getOctetStream(), secureValidation);
Added: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/AbstractDOMStreamReader.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/AbstractDOMStreamReader.java?rev=1847262&view=auto
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/AbstractDOMStreamReader.java (added)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/AbstractDOMStreamReader.java Fri Nov 23 13:30:09 2018
@@ -0,0 +1,361 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.staxutils;
+
+import java.util.Collections;
+import java.util.List;
+
+import javax.xml.stream.Location;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+
+/**
+ * Abstract logic for creating XMLStreamReader from DOM documents. Its works
+ * using adapters for Element, Node and Attribute.
+ */
+public abstract class AbstractDOMStreamReader<T, I> implements XMLStreamReader {
+ protected int currentEvent = XMLStreamConstants.START_DOCUMENT;
+
+ private FastStack<ElementFrame<T, I>> frames = new FastStack<>();
+
+ private ElementFrame<T, I> frame;
+
+
+ /**
+ *
+ */
+ public static class ElementFrame<T, I> {
+ T element;
+ I currentChild;
+
+ boolean started;
+ boolean ended;
+
+ List<String> uris;
+ List<String> prefixes;
+ List<Object> attributes;
+
+ final ElementFrame<T, I> parent;
+
+ public ElementFrame(T element, ElementFrame<T, I> parent) {
+ this.element = element;
+ this.parent = parent;
+ }
+
+ public ElementFrame(T element, ElementFrame<T, I> parent, I ch) {
+ this.element = element;
+ this.parent = parent;
+ this.currentChild = ch;
+ }
+ public ElementFrame(T doc, boolean s) {
+ this.element = doc;
+ parent = null;
+ started = s;
+ attributes = Collections.emptyList();
+ prefixes = Collections.emptyList();
+ uris = Collections.emptyList();
+ }
+ public ElementFrame(T doc) {
+ this(doc, true);
+ }
+ public T getElement() {
+ return element;
+ }
+
+ public I getCurrentChild() {
+ return currentChild;
+ }
+ public void setCurrentChild(I o) {
+ currentChild = o;
+ }
+ public boolean isDocument() {
+ return false;
+ }
+ public boolean isDocumentFragment() {
+ return false;
+ }
+ }
+
+ /**
+ * @param frame
+ */
+ public AbstractDOMStreamReader(ElementFrame<T, I> frame) {
+ this.frame = frame;
+ frames.push(this.frame);
+ }
+
+ protected ElementFrame<T, I> getCurrentFrame() {
+ return frame;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#getProperty(java.lang.String)
+ */
+ public Object getProperty(String key) throws IllegalArgumentException {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#next()
+ */
+ public int next() throws XMLStreamException {
+ if (frame.ended) {
+ frames.pop();
+ if (!frames.empty()) {
+ frame = frames.peek();
+ } else {
+ currentEvent = END_DOCUMENT;
+ return currentEvent;
+ }
+ }
+
+ if (!frame.started) {
+ frame.started = true;
+ currentEvent = frame.isDocument() ? START_DOCUMENT : START_ELEMENT;
+ } else if (hasMoreChildren()) {
+ currentEvent = nextChild();
+
+ if (currentEvent == START_ELEMENT) {
+ ElementFrame<T, I> newFrame = getChildFrame();
+ newFrame.started = true;
+ frame = newFrame;
+ frames.push(this.frame);
+ currentEvent = START_ELEMENT;
+
+ newFrame(newFrame);
+ }
+ } else {
+ frame.ended = true;
+ if (frame.isDocument()) {
+ currentEvent = END_DOCUMENT;
+ } else {
+ currentEvent = END_ELEMENT;
+ endElement();
+ }
+ }
+ return currentEvent;
+ }
+
+ protected void newFrame(ElementFrame<T, I> newFrame) {
+ }
+
+ protected void endElement() {
+ }
+
+ protected abstract boolean hasMoreChildren();
+ protected abstract int nextChild();
+ protected abstract ElementFrame<T, I> getChildFrame();
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#require(int, java.lang.String,
+ * java.lang.String)
+ */
+ public void require(int arg0, String arg1, String arg2) throws XMLStreamException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#getElementText()
+ */
+ public abstract String getElementText() throws XMLStreamException;
+
+ public void consumeFrame() {
+ frame.started = true;
+ frame.ended = true;
+ if (frame.isDocument()) {
+ currentEvent = END_DOCUMENT;
+ } else {
+ currentEvent = END_ELEMENT;
+ endElement();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#nextTag()
+ */
+ public int nextTag() throws XMLStreamException {
+ while (hasNext()) {
+ if (START_ELEMENT == next()) {
+ return START_ELEMENT;
+ }
+ }
+
+ return currentEvent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#hasNext()
+ */
+ public boolean hasNext() throws XMLStreamException {
+
+ return !(frame.ended && (frames.isEmpty() || frame.isDocumentFragment()));
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#close()
+ */
+ public void close() throws XMLStreamException {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#getNamespaceURI(java.lang.String)
+ */
+ public abstract String getNamespaceURI(String prefix);
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isStartElement()
+ */
+ public boolean isStartElement() {
+ return currentEvent == START_ELEMENT;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isEndElement()
+ */
+ public boolean isEndElement() {
+ return currentEvent == END_ELEMENT;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isCharacters()
+ */
+ public boolean isCharacters() {
+ return currentEvent == CHARACTERS;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isWhiteSpace()
+ */
+ public boolean isWhiteSpace() {
+ if (currentEvent == CHARACTERS || currentEvent == CDATA) {
+ String text = getText();
+ int len = text.length();
+ for (int i = 0; i < len; ++i) {
+ if (text.charAt(i) > 0x0020) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return currentEvent == SPACE;
+ }
+
+ public int getEventType() {
+ return currentEvent;
+ }
+
+ public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length)
+ throws XMLStreamException {
+ char[] src = getText().toCharArray();
+
+ if (sourceStart + length >= src.length) {
+ length = src.length - sourceStart;
+ }
+
+ for (int i = 0; i < length; i++) {
+ target[targetStart + i] = src[i + sourceStart];
+ }
+
+ return length;
+ }
+
+ public boolean hasText() {
+ return currentEvent == CHARACTERS || currentEvent == DTD || currentEvent == ENTITY_REFERENCE
+ || currentEvent == COMMENT || currentEvent == SPACE;
+ }
+
+ public String getSystemId() {
+ return null;
+ }
+ public String getPublicId() {
+ return null;
+ }
+ public Location getLocation() {
+ return new Location() {
+
+ public int getCharacterOffset() {
+ return 0;
+ }
+
+ public int getColumnNumber() {
+ return 0;
+ }
+
+ public int getLineNumber() {
+ return 0;
+ }
+
+ public String getPublicId() {
+ return AbstractDOMStreamReader.this.getPublicId();
+ }
+
+ public String getSystemId() {
+ return AbstractDOMStreamReader.this.getSystemId();
+ }
+
+ };
+ }
+
+ public boolean hasName() {
+ return currentEvent == START_ELEMENT || currentEvent == END_ELEMENT;
+ }
+
+ public String getVersion() {
+ return null;
+ }
+
+ public boolean isStandalone() {
+ return false;
+ }
+
+ public boolean standaloneSet() {
+ return false;
+ }
+
+ public String getCharacterEncodingScheme() {
+ return null;
+ }
+}
Added: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DOMUtils.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DOMUtils.java?rev=1847262&view=auto
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DOMUtils.java (added)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DOMUtils.java Fri Nov 23 13:30:09 2018
@@ -0,0 +1,142 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.xml.security.staxutils;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.Collections;
+import java.util.Map;
+import java.util.WeakHashMap;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+
+/**
+ * Few simple utils to read DOM. This is originally from the Jakarta Commons Modeler.
+ */
+public final class DOMUtils {
+ private static final Map<ClassLoader, DocumentBuilder> DOCUMENT_BUILDERS
+ = Collections.synchronizedMap(new WeakHashMap<ClassLoader, DocumentBuilder>());
+ private static final Map<ClassLoader, DocumentBuilder> DOCUMENT_BUILDERS_DISALLOW_DOCTYPE
+ = Collections.synchronizedMap(new WeakHashMap<ClassLoader, DocumentBuilder>());
+
+ private DOMUtils() {
+ }
+
+ private static DocumentBuilder getDocumentBuilder(boolean disAllowDocTypeDeclarations) throws ParserConfigurationException {
+ ClassLoader loader = getContextClassLoader();
+ if (loader == null) {
+ loader = getClassLoader(DOMUtils.class);
+ }
+ if (loader == null) {
+ DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
+ f.setNamespaceAware(true);
+ f.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", disAllowDocTypeDeclarations);
+ return f.newDocumentBuilder();
+ }
+ DocumentBuilder factory =
+ disAllowDocTypeDeclarations ? DOCUMENT_BUILDERS_DISALLOW_DOCTYPE.get(loader) : DOCUMENT_BUILDERS.get(loader);
+ if (factory == null) {
+ DocumentBuilderFactory f2 = DocumentBuilderFactory.newInstance();
+ f2.setNamespaceAware(true);
+ f2.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ f2.setFeature("http://apache.org/xml/features/disallow-doctype-decl", disAllowDocTypeDeclarations);
+ factory = f2.newDocumentBuilder();
+ if (disAllowDocTypeDeclarations) {
+ DOCUMENT_BUILDERS_DISALLOW_DOCTYPE.put(loader, factory);
+ } else {
+ DOCUMENT_BUILDERS.put(loader, factory);
+ }
+ }
+ return factory;
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
+ public ClassLoader run() {
+ return Thread.currentThread().getContextClassLoader();
+ }
+ });
+ }
+ return Thread.currentThread().getContextClassLoader();
+ }
+
+ private static ClassLoader getClassLoader(final Class<?> clazz) {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
+ public ClassLoader run() {
+ return clazz.getClassLoader();
+ }
+ });
+ }
+ return clazz.getClassLoader();
+ }
+
+ /**
+ * Creates a new Document object
+ * @throws ParserConfigurationException
+ */
+ public static Document newDocument(boolean disAllowDocTypeDeclarations) {
+ try {
+ return getDocumentBuilder(disAllowDocTypeDeclarations).newDocument();
+ } catch (ParserConfigurationException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Get the raw text content of a node or null if there is no text
+ */
+ public static String getRawContent(Node n) {
+ if (n == null) {
+ return null;
+ }
+ StringBuilder b = null;
+ String s = null;
+ Node n1 = n.getFirstChild();
+ while (n1 != null) {
+ if (n1.getNodeType() == Node.TEXT_NODE || n1.getNodeType() == Node.CDATA_SECTION_NODE) {
+ if (b != null) {
+ b.append(((Text)n1).getNodeValue());
+ } else if (s == null) {
+ s = ((Text)n1).getNodeValue();
+ } else {
+ b = new StringBuilder(s).append(((Text)n1).getNodeValue());
+ s = null;
+ }
+ }
+ n1 = n1.getNextSibling();
+ }
+ if (b != null) {
+ return b.toString();
+ }
+ return s;
+ }
+
+}
Copied: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthExceededStaxException.java (from r1847258, santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java)
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthExceededStaxException.java?p2=santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthExceededStaxException.java&p1=santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java&r1=1847258&r2=1847262&rev=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthExceededStaxException.java Fri Nov 23 13:30:09 2018
@@ -16,30 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.xml.security.test.dom;
+package org.apache.xml.security.staxutils;
-import org.apache.xml.security.utils.Constants;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class TestUtils {
-
- /**
- * Method createDSctx
- *
- * @param doc
- * @param prefix
- * @param namespace
- * @return the element.
- */
- public static Element createDSctx(Document doc, String prefix, String namespace) {
- if (prefix == null || prefix.trim().length() == 0) {
- throw new IllegalArgumentException("You must supply a prefix");
- }
-
- Element ctx = doc.createElementNS(null, "namespaceContext");
- ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace);
- return ctx;
+public class DepthExceededStaxException extends RuntimeException {
+
+ private static final long serialVersionUID = 4750070687283463619L;
+
+ public DepthExceededStaxException() {
+
+ }
+
+ public DepthExceededStaxException(String message) {
+ super(message);
}
}
Added: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthRestrictingStreamReader.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthRestrictingStreamReader.java?rev=1847262&view=auto
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthRestrictingStreamReader.java (added)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthRestrictingStreamReader.java Fri Nov 23 13:30:09 2018
@@ -0,0 +1,84 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.staxutils;
+
+import java.util.Stack;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+/**
+ * XMLStreamReader implementation which can be used to enforce a number of
+ * depth-restricting policies. The following properties are currently supported:
+ * - total number of elements in the document
+ * - the maximum depth of the given element; the root element will be checked by default
+ * - the maximum number of immediate child nodes for individual elements
+ *
+ * More sophisticated policies can be supported in the future.
+ */
+public class DepthRestrictingStreamReader extends DepthXMLStreamReader {
+
+ private DocumentDepthProperties props;
+ private int totalElementCount;
+ private Stack<Integer> stack = new Stack<>();
+
+ public DepthRestrictingStreamReader(XMLStreamReader reader,
+ int elementCountThreshold,
+ int innerElementLevelThreshold,
+ int innerElementCountThreshold) {
+ this(reader, new DocumentDepthProperties(elementCountThreshold,
+ innerElementLevelThreshold,
+ innerElementCountThreshold));
+ }
+
+ public DepthRestrictingStreamReader(XMLStreamReader reader,
+ DocumentDepthProperties props) {
+ super(reader);
+ this.props = props;
+ }
+
+ @Override
+ public int next() throws XMLStreamException {
+ int next = super.next();
+ if (next == START_ELEMENT) {
+ if (props.getInnerElementLevelThreshold() != -1
+ && getDepth() >= props.getInnerElementLevelThreshold()) {
+ throw new DepthExceededStaxException();
+ }
+ if (props.getElementCountThreshold() != -1
+ && ++totalElementCount >= props.getElementCountThreshold()) {
+ throw new DepthExceededStaxException();
+ }
+ if (props.getInnerElementCountThreshold() != -1) {
+ if (!stack.empty()) {
+ int currentCount = stack.pop();
+ if (++currentCount >= props.getInnerElementCountThreshold()) {
+ throw new DepthExceededStaxException();
+ }
+ stack.push(currentCount);
+ }
+ stack.push(0);
+ }
+
+ } else if (next == END_ELEMENT && props.getInnerElementCountThreshold() != -1) {
+ stack.pop();
+ }
+ return next;
+ }
+}
Added: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthXMLStreamReader.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthXMLStreamReader.java?rev=1847262&view=auto
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthXMLStreamReader.java (added)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DepthXMLStreamReader.java Fri Nov 23 13:30:09 2018
@@ -0,0 +1,266 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.xml.security.staxutils;
+
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+import javax.xml.stream.Location;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+public class DepthXMLStreamReader implements XMLStreamReader {
+
+ protected XMLStreamReader reader;
+ private int depth;
+
+ public DepthXMLStreamReader(XMLStreamReader r) {
+ this.reader = r;
+ }
+
+ public XMLStreamReader getReader() {
+ return this.reader;
+ }
+
+ public int getDepth() {
+ return depth;
+ }
+
+ public void close() throws XMLStreamException {
+ reader.close();
+ }
+
+ public int getAttributeCount() {
+ return reader.getAttributeCount();
+ }
+
+ public String getAttributeLocalName(int arg0) {
+ return reader.getAttributeLocalName(arg0);
+ }
+
+ public QName getAttributeName(int arg0) {
+ return reader.getAttributeName(arg0);
+ }
+
+ public String getAttributeNamespace(int arg0) {
+ return reader.getAttributeNamespace(arg0);
+ }
+
+ public String getAttributePrefix(int arg0) {
+ return reader.getAttributePrefix(arg0);
+ }
+
+ public String getAttributeType(int arg0) {
+ return reader.getAttributeType(arg0);
+ }
+
+ public String getAttributeValue(int arg0) {
+ return reader.getAttributeValue(arg0);
+ }
+
+ public String getAttributeValue(String namespace, String localName) {
+ return reader.getAttributeValue(namespace, localName);
+ }
+
+ public String getCharacterEncodingScheme() {
+ return reader.getCharacterEncodingScheme();
+ }
+
+ public String getElementText() throws XMLStreamException {
+ String ret = reader.getElementText();
+ //workaround bugs in some readers that aren't properly advancing to
+ //the END_ELEMENT (*cough*jettison*cough*)
+ while (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
+ reader.next();
+ }
+ depth--;
+ return ret;
+ }
+
+ public String getEncoding() {
+ return reader.getEncoding();
+ }
+
+ public int getEventType() {
+ return reader.getEventType();
+ }
+
+ public String getLocalName() {
+ return reader.getLocalName();
+ }
+
+ public Location getLocation() {
+ return reader.getLocation();
+ }
+
+ public QName getName() {
+ return reader.getName();
+ }
+
+ public NamespaceContext getNamespaceContext() {
+ return reader.getNamespaceContext();
+ }
+
+ public int getNamespaceCount() {
+ return reader.getNamespaceCount();
+ }
+
+ public String getNamespacePrefix(int arg0) {
+ return reader.getNamespacePrefix(arg0);
+ }
+
+ public String getNamespaceURI() {
+ return reader.getNamespaceURI();
+ }
+
+ public String getNamespaceURI(int arg0) {
+
+ return reader.getNamespaceURI(arg0);
+ }
+
+ public String getNamespaceURI(String arg0) {
+ return reader.getNamespaceURI(arg0);
+ }
+
+ public String getPIData() {
+ return reader.getPIData();
+ }
+
+ public String getPITarget() {
+ return reader.getPITarget();
+ }
+
+ public String getPrefix() {
+ return reader.getPrefix();
+ }
+
+ public Object getProperty(String arg0) throws IllegalArgumentException {
+
+ return reader.getProperty(arg0);
+ }
+
+ public String getText() {
+ return reader.getText();
+ }
+
+ public char[] getTextCharacters() {
+ return reader.getTextCharacters();
+ }
+
+ public int getTextCharacters(int arg0, char[] arg1, int arg2, int arg3) throws XMLStreamException {
+ return reader.getTextCharacters(arg0, arg1, arg2, arg3);
+ }
+
+ public int getTextLength() {
+ return reader.getTextLength();
+ }
+
+ public int getTextStart() {
+ return reader.getTextStart();
+ }
+
+ public String getVersion() {
+ return reader.getVersion();
+ }
+
+ public boolean hasName() {
+ return reader.hasName();
+ }
+
+ public boolean hasNext() throws XMLStreamException {
+ return reader.hasNext();
+ }
+
+ public boolean hasText() {
+ return reader.hasText();
+ }
+
+ public boolean isAttributeSpecified(int arg0) {
+ return reader.isAttributeSpecified(arg0);
+ }
+
+ public boolean isCharacters() {
+ return reader.isCharacters();
+ }
+
+ public boolean isEndElement() {
+ return reader.isEndElement();
+ }
+
+ public boolean isStandalone() {
+ return reader.isStandalone();
+ }
+
+ public boolean isStartElement() {
+ return reader.isStartElement();
+ }
+
+ public boolean isWhiteSpace() {
+ return reader.isWhiteSpace();
+ }
+
+ public int next() throws XMLStreamException {
+ int next = reader.next();
+
+ if (next == START_ELEMENT) {
+ depth++;
+ } else if (next == END_ELEMENT) {
+ depth--;
+ }
+
+ return next;
+ }
+
+ public int nextTag() throws XMLStreamException {
+ int eventType = next();
+ while (eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()
+ || eventType == XMLStreamConstants.CDATA && isWhiteSpace()
+ // skip whitespace
+ || eventType == XMLStreamConstants.SPACE
+ || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
+ || eventType == XMLStreamConstants.COMMENT) {
+ eventType = next();
+ }
+ if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
+ throw new XMLStreamException("expected start or end tag", getLocation());
+ }
+ return eventType;
+ }
+
+ public void require(int arg0, String arg1, String arg2) throws XMLStreamException {
+ reader.require(arg0, arg1, arg2);
+ }
+
+ public boolean standaloneSet() {
+ return reader.standaloneSet();
+ }
+
+ public int hashCode() {
+ return reader.hashCode();
+ }
+
+ public boolean equals(Object arg0) {
+ return reader.equals(arg0);
+ }
+
+ public String toString() {
+ return reader.toString();
+ }
+}
Added: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DocumentDepthProperties.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DocumentDepthProperties.java?rev=1847262&view=auto
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DocumentDepthProperties.java (added)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/DocumentDepthProperties.java Fri Nov 23 13:30:09 2018
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.staxutils;
+
+public class DocumentDepthProperties {
+
+ public static final String TOTAL_ELEMENT_COUNT = "depthTotalElementCountThreshold";
+ public static final String INNER_ELEMENT_COUNT = "depthInnerElementCountThreshold";
+ public static final String INNER_ELEMENT_LEVEL = "depthInnerElementLevelThreshold";
+
+ private int elementCountThreshold = -1;
+ private int innerElementLevelThreshold = -1;
+ private int innerElementCountThreshold = -1;
+ public DocumentDepthProperties() {
+
+ }
+ public DocumentDepthProperties(int elementCountThreshold,
+ int innerElementLevelThreshold,
+ int innerElementCountThreshold) {
+ this.elementCountThreshold = elementCountThreshold;
+ this.innerElementLevelThreshold = innerElementLevelThreshold;
+ this.innerElementCountThreshold = innerElementCountThreshold;
+ }
+
+ public boolean isEffective() {
+ return elementCountThreshold != -1 || innerElementLevelThreshold != -1
+ || innerElementCountThreshold != -1;
+ }
+
+ public void setElementCountThreshold(int elementCountThreshold) {
+ this.elementCountThreshold = elementCountThreshold;
+ }
+ public int getElementCountThreshold() {
+ return elementCountThreshold;
+ }
+ public void setInnerElementLevelThreshold(int innerElementLevelThreshold) {
+ this.innerElementLevelThreshold = innerElementLevelThreshold;
+ }
+ public int getInnerElementLevelThreshold() {
+ return innerElementLevelThreshold;
+ }
+ public void setInnerElementCountThreshold(int innerElementCountThreshold) {
+ this.innerElementCountThreshold = innerElementCountThreshold;
+ }
+ public int getInnerElementCountThreshold() {
+ return innerElementCountThreshold;
+ }
+}
Copied: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/FastStack.java (from r1847258, santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java)
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/FastStack.java?p2=santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/FastStack.java&p1=santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java&r1=1847258&r2=1847262&rev=1847262&view=diff
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/test/java/org/apache/xml/security/test/dom/TestUtils.java (original)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/FastStack.java Fri Nov 23 13:30:09 2018
@@ -16,30 +16,35 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.xml.security.test.dom;
+package org.apache.xml.security.staxutils;
-import org.apache.xml.security.utils.Constants;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class TestUtils {
-
- /**
- * Method createDSctx
- *
- * @param doc
- * @param prefix
- * @param namespace
- * @return the element.
- */
- public static Element createDSctx(Document doc, String prefix, String namespace) {
- if (prefix == null || prefix.trim().length() == 0) {
- throw new IllegalArgumentException("You must supply a prefix");
+import java.util.ArrayList;
+import java.util.EmptyStackException;
+
+public class FastStack<T> extends ArrayList<T> {
+ private static final long serialVersionUID = -6459503295618120689L;
+
+ public void push(T o) {
+ add(o);
+ }
+
+ public T pop() {
+ if (empty()) {
+ throw new EmptyStackException();
}
- Element ctx = doc.createElementNS(null, "namespaceContext");
- ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace);
- return ctx;
+ return remove(size() - 1);
}
+ public boolean empty() {
+ return size() == 0;
+ }
+
+ public T peek() {
+ if (empty()) {
+ throw new EmptyStackException();
+ }
+
+ return get(size() - 1);
+ }
}
Added: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/StaxUtils.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/StaxUtils.java?rev=1847262&view=auto
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/StaxUtils.java (added)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/StaxUtils.java Fri Nov 23 13:30:09 2018
@@ -0,0 +1,592 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.xml.security.staxutils;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.Stack;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.stream.Location;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLResolver;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.sax.SAXSource;
+import javax.xml.transform.stax.StAXSource;
+import javax.xml.transform.stream.StreamSource;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.UserDataHandler;
+import org.xml.sax.InputSource;
+
+public final class StaxUtils {
+
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(StaxUtils.class);
+
+ private static final String XML_NS = "http://www.w3.org/2000/xmlns/";
+
+ private static final BlockingQueue<XMLInputFactory> DISALLOW_DOCTYPE_INPUT_FACTORY_POOL = new ArrayBlockingQueue<>(20);
+ private static final BlockingQueue<XMLInputFactory> ALLOW_DOCTYPE_INPUT_FACTORY_POOL = new ArrayBlockingQueue<>(20);
+
+ private StaxUtils() {
+ }
+
+ /**
+ * Return a cached, namespace-aware, factory.
+ */
+ private static XMLInputFactory getXMLInputFactory(boolean disAllowDocTypeDeclarations) {
+ XMLInputFactory f = disAllowDocTypeDeclarations
+ ? DISALLOW_DOCTYPE_INPUT_FACTORY_POOL.poll() : ALLOW_DOCTYPE_INPUT_FACTORY_POOL.poll();
+ if (f == null) {
+ f = createXMLInputFactory(disAllowDocTypeDeclarations);
+ }
+ return f;
+ }
+
+ private static void returnXMLInputFactory(XMLInputFactory factory, boolean disAllowDocTypeDeclarations) {
+ if (disAllowDocTypeDeclarations) {
+ DISALLOW_DOCTYPE_INPUT_FACTORY_POOL.offer(factory);
+ } else {
+ ALLOW_DOCTYPE_INPUT_FACTORY_POOL.offer(factory);
+ }
+ }
+
+ /**
+ * Return a new factory so that the caller can set sticky parameters.
+ * @param disAllowDocTypeDeclarations
+ * @throws XMLStreamException
+ */
+ private static XMLInputFactory createXMLInputFactory(boolean disAllowDocTypeDeclarations) {
+ XMLInputFactory factory = null;
+ try {
+ factory = XMLInputFactory.newInstance();
+ } catch (Throwable t) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("XMLInputFactory.newInstance() failed with: ", t);
+ }
+ throw new RuntimeException("Failed to create XMLInputFactory.");
+ }
+
+ setProperty(factory, XMLInputFactory.IS_NAMESPACE_AWARE, true);
+
+ if (disAllowDocTypeDeclarations) {
+ setProperty(factory, XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
+ setProperty(factory, XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE);
+ setProperty(factory, XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
+ factory.setXMLResolver(new XMLResolver() {
+ public Object resolveEntity(String publicID, String systemID,
+ String baseURI, String namespace)
+ throws XMLStreamException {
+ throw new XMLStreamException("Reading external entities is disabled");
+ }
+ });
+ }
+
+ return factory;
+ }
+
+ private static boolean setProperty(XMLInputFactory f, String p, Object o) {
+ try {
+ f.setProperty(p, o);
+ return true;
+ } catch (Throwable t) {
+ //ignore
+ }
+ return false;
+ }
+
+ public static Document read(Source s, boolean disAllowDocTypeDeclarations) throws XMLStreamException {
+ XMLStreamReader reader = createXMLStreamReader(s, disAllowDocTypeDeclarations);
+ try {
+ return read(reader);
+ } finally {
+ try {
+ reader.close();
+ } catch (Exception ex) {
+ //ignore
+ }
+ }
+ }
+ public static Document read(InputStream s, boolean disAllowDocTypeDeclarations) throws XMLStreamException {
+ XMLStreamReader reader = createXMLStreamReader(s, disAllowDocTypeDeclarations);
+ try {
+ return read(reader);
+ } finally {
+ try {
+ reader.close();
+ } catch (Exception ex) {
+ //ignore
+ }
+ }
+ }
+ public static Document read(Reader s, boolean disAllowDocTypeDeclarations) throws XMLStreamException {
+ XMLStreamReader reader = createXMLStreamReader(s, disAllowDocTypeDeclarations);
+ try {
+ return read(reader);
+ } finally {
+ try {
+ reader.close();
+ } catch (Exception ex) {
+ //ignore
+ }
+ }
+ }
+ public static Document read(File is, boolean disAllowDocTypeDeclarations) throws XMLStreamException, IOException {
+ try (InputStream fin = Files.newInputStream(is.toPath())) {
+ return read(fin, disAllowDocTypeDeclarations);
+ }
+ }
+ public static Document read(InputSource s, boolean disAllowDocTypeDeclarations) throws XMLStreamException {
+ XMLStreamReader reader = createXMLStreamReader(s, disAllowDocTypeDeclarations);
+ try {
+ return read(reader);
+ } finally {
+ try {
+ reader.close();
+ } catch (Exception ex) {
+ //ignore
+ }
+ }
+ }
+ public static Document read(XMLStreamReader reader) throws XMLStreamException {
+ return read(reader, false);
+ }
+ public static Document read(XMLStreamReader reader, boolean recordLoc) throws XMLStreamException {
+ Document doc = DOMUtils.newDocument(true);
+ if (reader.getLocation().getSystemId() != null) {
+ try {
+ doc.setDocumentURI(reader.getLocation().getSystemId());
+ } catch (Exception e) {
+ //ignore - probably not DOM level 3
+ }
+ }
+ readDocElements(doc, doc, reader, true, recordLoc);
+ return doc;
+ }
+
+ public static Document read(DocumentBuilder builder, XMLStreamReader reader, boolean repairing)
+ throws XMLStreamException {
+
+ Document doc = builder == null ? DOMUtils.newDocument(true) : builder.newDocument();
+ if (reader.getLocation().getSystemId() != null) {
+ try {
+ doc.setDocumentURI(reader.getLocation().getSystemId());
+ } catch (Exception e) {
+ //ignore - probably not DOM level 3
+ }
+ }
+ readDocElements(doc, reader, repairing);
+ return doc;
+ }
+
+ /**
+ * @param parent
+ */
+ private static Document getDocument(Node parent) {
+ return parent instanceof Document ? (Document)parent : parent.getOwnerDocument();
+ }
+
+ private static boolean isDeclared(Element e, String namespaceURI, String prefix) {
+ while (e != null) {
+ Attr att;
+ if (prefix != null && prefix.length() > 0) {
+ att = e.getAttributeNodeNS(XML_NS, prefix);
+ } else {
+ att = e.getAttributeNode("xmlns");
+ }
+
+ if (att != null && att.getNodeValue().equals(namespaceURI)) {
+ return true;
+ }
+
+ if (e.getParentNode() instanceof Element) {
+ e = (Element)e.getParentNode();
+ } else if (isEmpty(prefix) && isEmpty(namespaceURI)) {
+ //A document that probably doesn't have any namespace qualifies elements
+ return true;
+ } else {
+ e = null;
+ }
+ }
+ return false;
+ }
+
+ public static void readDocElements(Node parent, XMLStreamReader reader, boolean repairing)
+ throws XMLStreamException {
+ Document doc = getDocument(parent);
+ readDocElements(doc, parent, reader, repairing, false);
+ }
+
+ public static void readDocElements(Node parent, XMLStreamReader reader, boolean repairing,
+ boolean isThreshold)
+ throws XMLStreamException {
+ Document doc = getDocument(parent);
+ readDocElements(doc, parent, reader, repairing, false, isThreshold);
+ }
+
+ /**
+ * @param parent
+ * @param reader
+ * @throws XMLStreamException
+ */
+ public static void readDocElements(Document doc, Node parent,
+ XMLStreamReader reader, boolean repairing, boolean recordLoc)
+ throws XMLStreamException {
+ readDocElements(doc, parent, reader, repairing, recordLoc, false);
+ }
+
+ /**
+ * @param parent
+ * @param reader
+ * @throws XMLStreamException
+ */
+ public static void readDocElements(Document doc, Node parent,
+ XMLStreamReader reader, boolean repairing, boolean recordLoc,
+ boolean isThreshold)
+ throws XMLStreamException {
+ Stack<Node> stack = new Stack<Node>();
+ int event = reader.getEventType();
+ while (reader.hasNext()) {
+ switch (event) {
+ case XMLStreamConstants.START_ELEMENT: {
+ Element e;
+ if (!isEmpty(reader.getPrefix())) {
+ e = doc.createElementNS(reader.getNamespaceURI(),
+ reader.getPrefix() + ":" + reader.getLocalName());
+ } else {
+ e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName());
+ }
+ e = (Element)parent.appendChild(e);
+ recordLoc = addLocation(doc, e, reader, recordLoc);
+
+ for (int ns = 0; ns < reader.getNamespaceCount(); ns++) {
+ String uri = reader.getNamespaceURI(ns);
+ String prefix = reader.getNamespacePrefix(ns);
+
+ declare(e, uri, prefix);
+ }
+
+ for (int att = 0; att < reader.getAttributeCount(); att++) {
+ String name = reader.getAttributeLocalName(att);
+ String prefix = reader.getAttributePrefix(att);
+ if (prefix != null && prefix.length() > 0) {
+ name = prefix + ":" + name;
+ }
+
+ Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name);
+ attr.setValue(reader.getAttributeValue(att));
+ e.setAttributeNode(attr);
+ }
+
+ if (repairing && !isDeclared(e, reader.getNamespaceURI(), reader.getPrefix())) {
+ declare(e, reader.getNamespaceURI(), reader.getPrefix());
+ }
+ stack.push(parent);
+ parent = e;
+ break;
+ }
+ case XMLStreamConstants.END_ELEMENT:
+ if (stack.isEmpty()) {
+ return;
+ }
+ parent = stack.pop();
+ //if (parent instanceof Document || parent instanceof DocumentFragment) {
+ // return;
+ //}
+ break;
+ case XMLStreamConstants.NAMESPACE:
+ break;
+ case XMLStreamConstants.ATTRIBUTE:
+ break;
+ case XMLStreamConstants.CHARACTERS:
+ if (parent != null) {
+ recordLoc = addLocation(doc,
+ parent.appendChild(doc.createTextNode(reader.getText())),
+ reader, recordLoc);
+ }
+ break;
+ case XMLStreamConstants.COMMENT:
+ if (parent != null) {
+ parent.appendChild(doc.createComment(reader.getText()));
+ }
+ break;
+ case XMLStreamConstants.CDATA:
+ recordLoc = addLocation(doc,
+ parent.appendChild(doc.createCDATASection(reader.getText())),
+ reader, recordLoc);
+ break;
+ case XMLStreamConstants.PROCESSING_INSTRUCTION:
+ parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
+ break;
+ case XMLStreamConstants.ENTITY_REFERENCE:
+ parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
+ break;
+ default:
+ break;
+ }
+
+ if (reader.hasNext()) {
+ event = reader.next();
+ }
+ }
+ }
+
+ private static boolean addLocation(Document doc, Node node,
+ Location loc,
+ boolean recordLoc) {
+ if (recordLoc && loc != null && (loc.getColumnNumber() != 0 || loc.getLineNumber() != 0)) {
+ try {
+ final int charOffset = loc.getCharacterOffset();
+ final int colNum = loc.getColumnNumber();
+ final int linNum = loc.getLineNumber();
+ final String pubId = loc.getPublicId() == null ? doc.getDocumentURI() : loc.getPublicId();
+ final String sysId = loc.getSystemId() == null ? doc.getDocumentURI() : loc.getSystemId();
+ Location loc2 = new Location() {
+ public int getCharacterOffset() {
+ return charOffset;
+ }
+ public int getColumnNumber() {
+ return colNum;
+ }
+ public int getLineNumber() {
+ return linNum;
+ }
+ public String getPublicId() {
+ return pubId;
+ }
+ public String getSystemId() {
+ return sysId;
+ }
+ };
+ node.setUserData("location", loc2, LocationUserDataHandler.INSTANCE);
+ } catch (Throwable ex) {
+ //possibly not DOM level 3, won't be able to record this then
+ return false;
+ }
+ }
+ return recordLoc;
+ }
+
+ private static boolean addLocation(Document doc, Node node,
+ XMLStreamReader reader,
+ boolean recordLoc) {
+ return addLocation(doc, node, reader.getLocation(), recordLoc);
+ }
+
+ private static class LocationUserDataHandler implements UserDataHandler {
+ public static final LocationUserDataHandler INSTANCE = new LocationUserDataHandler();
+
+ public void handle(short operation, String key, Object data, Node src, Node dst) {
+ if (operation == NODE_CLONED) {
+ dst.setUserData(key, data, this);
+ }
+ }
+ }
+
+ private static void declare(Element node, String uri, String prefix) {
+ String qualname;
+ if (prefix != null && prefix.length() > 0) {
+ qualname = "xmlns:" + prefix;
+ } else {
+ qualname = "xmlns";
+ }
+ Attr attr = node.getOwnerDocument().createAttributeNS(XML_NS, qualname);
+ attr.setValue(uri);
+ node.setAttributeNodeNS(attr);
+ }
+
+ public static XMLStreamReader createXMLStreamReader(InputSource src, boolean disAllowDocTypeDeclarations) {
+ String sysId = src.getSystemId() == null ? null : src.getSystemId();
+ String pubId = src.getPublicId() == null ? null : src.getPublicId();
+ if (src.getByteStream() != null) {
+ if (src.getEncoding() == null) {
+ StreamSource ss = new StreamSource(src.getByteStream(), sysId);
+ ss.setPublicId(pubId);
+ return createXMLStreamReader(ss, disAllowDocTypeDeclarations);
+ }
+ return createXMLStreamReader(src.getByteStream(), src.getEncoding(), disAllowDocTypeDeclarations);
+ } else if (src.getCharacterStream() != null) {
+ StreamSource ss = new StreamSource(src.getCharacterStream(), sysId);
+ ss.setPublicId(pubId);
+ return createXMLStreamReader(ss, disAllowDocTypeDeclarations);
+ } else {
+ try {
+ URL url = new URL(sysId);
+ StreamSource ss = new StreamSource(url.openStream(), sysId);
+ ss.setPublicId(pubId);
+ return createXMLStreamReader(ss, disAllowDocTypeDeclarations);
+ } catch (Exception ex) {
+ //ignore - not a valid URL
+ }
+ }
+ throw new IllegalArgumentException("InputSource must have a ByteStream or CharacterStream");
+ }
+ /**
+ * @param in
+ * @param encoding
+ */
+ public static XMLStreamReader createXMLStreamReader(InputStream in, String encoding, boolean disAllowDocTypeDeclarations) {
+ if (encoding == null) {
+ encoding = StandardCharsets.UTF_8.name();
+ }
+
+ XMLInputFactory factory = getXMLInputFactory(disAllowDocTypeDeclarations);
+ try {
+ return factory.createXMLStreamReader(in, encoding);
+ } catch (XMLStreamException e) {
+ throw new RuntimeException("Couldn't parse stream.", e);
+ } finally {
+ returnXMLInputFactory(factory, disAllowDocTypeDeclarations);
+ }
+ }
+
+ /**
+ * @param in
+ */
+ public static XMLStreamReader createXMLStreamReader(InputStream in, boolean disAllowDocTypeDeclarations) {
+ XMLInputFactory factory = getXMLInputFactory(disAllowDocTypeDeclarations);
+ try {
+ return factory.createXMLStreamReader(in);
+ } catch (XMLStreamException e) {
+ throw new RuntimeException("Couldn't parse stream.", e);
+ } finally {
+ returnXMLInputFactory(factory, disAllowDocTypeDeclarations);
+ }
+ }
+ public static XMLStreamReader createXMLStreamReader(String systemId, InputStream in, boolean disAllowDocTypeDeclarations) {
+ XMLInputFactory factory = getXMLInputFactory(disAllowDocTypeDeclarations);
+ try {
+ return factory.createXMLStreamReader(systemId, in);
+ } catch (XMLStreamException e) {
+ throw new RuntimeException("Couldn't parse stream.", e);
+ } finally {
+ returnXMLInputFactory(factory, disAllowDocTypeDeclarations);
+ }
+ }
+
+ public static XMLStreamReader createXMLStreamReader(Element el) {
+ return new W3CDOMStreamReader(el);
+ }
+ public static XMLStreamReader createXMLStreamReader(Document doc) {
+ return new W3CDOMStreamReader(doc.getDocumentElement());
+ }
+ public static XMLStreamReader createXMLStreamReader(Element el, String sysId) {
+ return new W3CDOMStreamReader(el, sysId);
+ }
+ public static XMLStreamReader createXMLStreamReader(Document doc, String sysId) {
+ return new W3CDOMStreamReader(doc.getDocumentElement(), sysId);
+ }
+
+ public static XMLStreamReader createXMLStreamReader(Source source, boolean disAllowDocTypeDeclarations) {
+ try {
+ if (source instanceof DOMSource) {
+ DOMSource ds = (DOMSource)source;
+ Node nd = ds.getNode();
+ Element el = null;
+ if (nd instanceof Document) {
+ el = ((Document)nd).getDocumentElement();
+ } else if (nd instanceof Element) {
+ el = (Element)nd;
+ }
+
+ if (null != el) {
+ return new W3CDOMStreamReader(el, source.getSystemId());
+ }
+ } else if (source instanceof StAXSource) {
+ return ((StAXSource)source).getXMLStreamReader();
+ } else if (source instanceof SAXSource) {
+ SAXSource ss = (SAXSource)source;
+ if (ss.getXMLReader() == null) {
+ return createXMLStreamReader(((SAXSource)source).getInputSource(), disAllowDocTypeDeclarations);
+ }
+ }
+
+ XMLInputFactory factory = getXMLInputFactory(disAllowDocTypeDeclarations);
+ try {
+ XMLStreamReader reader = null;
+
+ try {
+ reader = factory.createXMLStreamReader(source);
+ } catch (UnsupportedOperationException e) {
+ //ignore
+ }
+ if (reader == null && source instanceof StreamSource) {
+ //createXMLStreamReader from Source is optional, we'll try and map it
+ StreamSource ss = (StreamSource)source;
+ if (ss.getInputStream() != null) {
+ reader = factory.createXMLStreamReader(ss.getSystemId(),
+ ss.getInputStream());
+ } else {
+ reader = factory.createXMLStreamReader(ss.getSystemId(),
+ ss.getReader());
+ }
+ }
+ return reader;
+ } finally {
+ returnXMLInputFactory(factory, disAllowDocTypeDeclarations);
+ }
+ } catch (XMLStreamException e) {
+ throw new RuntimeException("Couldn't parse stream.", e);
+ }
+ }
+
+ /**
+ * @param reader
+ */
+ public static XMLStreamReader createXMLStreamReader(Reader reader, boolean disAllowDocTypeDeclarations) {
+ XMLInputFactory factory = getXMLInputFactory(disAllowDocTypeDeclarations);
+ try {
+ return factory.createXMLStreamReader(reader);
+ } catch (XMLStreamException e) {
+ throw new RuntimeException("Couldn't parse stream.", e);
+ } finally {
+ returnXMLInputFactory(factory, disAllowDocTypeDeclarations);
+ }
+ }
+
+ private static boolean isEmpty(String str) {
+ if (str != null) {
+ int len = str.length();
+ for (int x = 0; x < len; ++x) {
+ if (str.charAt(x) > ' ') {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+
+}
Added: santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/SystemPropertyAction.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/SystemPropertyAction.java?rev=1847262&view=auto
==============================================================================
--- santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/SystemPropertyAction.java (added)
+++ santuario/xml-security-java/branches/staxutils/src/main/java/org/apache/xml/security/staxutils/SystemPropertyAction.java Fri Nov 23 13:30:09 2018
@@ -0,0 +1,97 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.xml.security.staxutils;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+
+/**
+ *
+ */
+public final class SystemPropertyAction implements PrivilegedAction<String> {
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(SystemPropertyAction.class);
+ private final String property;
+ private final String def;
+ private SystemPropertyAction(String name) {
+ property = name;
+ def = null;
+ }
+ private SystemPropertyAction(String name, String d) {
+ property = name;
+ def = d;
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.PrivilegedAction#run()
+ */
+ public String run() {
+ if (def != null) {
+ return System.getProperty(property, def);
+ }
+ return System.getProperty(property);
+ }
+
+ public static String getProperty(String name) {
+ return AccessController.doPrivileged(new SystemPropertyAction(name));
+ }
+
+ public static String getProperty(String name, String def) {
+ try {
+ return AccessController.doPrivileged(new SystemPropertyAction(name, def));
+ } catch (SecurityException ex) {
+ LOG.debug("SecurityException raised getting property " + name, ex);
+ return def;
+ }
+ }
+
+ /**
+ * Get the system property via the AccessController, but if a SecurityException is
+ * raised, just return null;
+ * @param name
+ */
+ public static String getPropertyOrNull(String name) {
+ try {
+ return AccessController.doPrivileged(new SystemPropertyAction(name));
+ } catch (SecurityException ex) {
+ LOG.debug("SecurityException raised getting property " + name, ex);
+ return null;
+ }
+ }
+
+ /**
+ * Get the integer system property via the AccessController, but if a SecurityException is
+ * raised, just return the default;
+ * @param name - system property name
+ * @param def - the default value if the system property does not exist or cannot be acquired
+ */
+ public static int getInteger(String name, int def) {
+ try {
+ return AccessController.doPrivileged(new PrivilegedAction<Integer>() {
+ @Override
+ public Integer run() {
+ return Integer.getInteger(name, def);
+ } });
+ } catch (SecurityException ex) {
+ LOG.debug("SecurityException raised getting property " + name, ex);
+ return def;
+ }
+ }
+}