Converted spaces to tabs

This commit changes leading spaces in all Java source files to tabs, to
be consistent with other Spring projects.
This commit is contained in:
Arjen Poutsma
2015-03-18 09:33:06 +01:00
parent b6500fe5ac
commit 7d64bebd19
824 changed files with 46904 additions and 46904 deletions

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -32,64 +32,64 @@ import org.springframework.util.ClassUtils;
*/
public abstract class JaxpVersion {
/**
* Constant identifying JAXP 1.0.
*/
public static final int JAXP_10 = 0;
/**
* Constant identifying JAXP 1.0.
*/
public static final int JAXP_10 = 0;
/**
* Constant identifying JAXP 1.1.
*/
public static final int JAXP_11 = 1;
/**
* Constant identifying JAXP 1.1.
*/
public static final int JAXP_11 = 1;
/**
* Constant identifying JAXP 1.3.
*/
public static final int JAXP_13 = 3;
/**
* Constant identifying JAXP 1.3.
*/
public static final int JAXP_13 = 3;
/**
* Constant identifying JAXP 1.4.
*/
public static final int JAXP_14 = 4;
/**
* Constant identifying JAXP 1.4.
*/
public static final int JAXP_14 = 4;
private static final String JAXP_14_CLASS_NAME = "javax.xml.transform.stax.StAXSource";
private static final String JAXP_14_CLASS_NAME = "javax.xml.transform.stax.StAXSource";
private static int jaxpVersion;
private static int jaxpVersion;
static {
ClassLoader classLoader = JaxpVersion.class.getClassLoader();
try {
ClassUtils.forName(JAXP_14_CLASS_NAME, classLoader);
jaxpVersion = JAXP_14;
}
catch (ClassNotFoundException ex) {
// leave 1.3 as default (it's either 1.3 or unknown)
jaxpVersion = JAXP_13;
}
}
static {
ClassLoader classLoader = JaxpVersion.class.getClassLoader();
try {
ClassUtils.forName(JAXP_14_CLASS_NAME, classLoader);
jaxpVersion = JAXP_14;
}
catch (ClassNotFoundException ex) {
// leave 1.3 as default (it's either 1.3 or unknown)
jaxpVersion = JAXP_13;
}
}
/**
* Gets the JAXP version. This means we can do things like if {@code (getJaxpVersion() < JAXP_13)}.
*
* @return a code comparable to the JAXP_XX codes in this class
* @see #JAXP_10
* @see #JAXP_11
* @see #JAXP_13
* @see #JAXP_14
*/
public static int getJaxpVersion() {
return jaxpVersion;
}
/**
* Gets the JAXP version. This means we can do things like if {@code (getJaxpVersion() < JAXP_13)}.
*
* @return a code comparable to the JAXP_XX codes in this class
* @see #JAXP_10
* @see #JAXP_11
* @see #JAXP_13
* @see #JAXP_14
*/
public static int getJaxpVersion() {
return jaxpVersion;
}
/**
* Convenience method to determine if the current JAXP version is at least 1.4 (packaged with JDK 1.6).
*
* @return {@code true} if the current JAXP version is at least JAXP 1.4
* @see #getJaxpVersion()
* @see #JAXP_14
*/
public static boolean isAtLeastJaxp14() {
return getJaxpVersion() >= JAXP_14;
}
/**
* Convenience method to determine if the current JAXP version is at least 1.4 (packaged with JDK 1.6).
*
* @return {@code true} if the current JAXP version is at least JAXP 1.4
* @see #getJaxpVersion()
* @see #JAXP_14
*/
public static boolean isAtLeastJaxp14() {
return getJaxpVersion() >= JAXP_14;
}
}

View File

@@ -27,22 +27,22 @@ import org.springframework.core.NestedRuntimeException;
@SuppressWarnings("serial")
public abstract class XmlException extends NestedRuntimeException {
/**
* Constructs a new instance of the {@code XmlException} with the specific detail message.
*
* @param message the detail message
*/
protected XmlException(String message) {
super(message);
}
/**
* Constructs a new instance of the {@code XmlException} with the specific detail message.
*
* @param message the detail message
*/
protected XmlException(String message) {
super(message);
}
/**
* Constructs a new instance of the {@code XmlException} with the specific detail message and exception.
*
* @param message the detail message
* @param throwable the wrapped exception
*/
protected XmlException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructs a new instance of the {@code XmlException} with the specific detail message and exception.
*
* @param message the detail message
* @param throwable the wrapped exception
*/
protected XmlException(String message, Throwable throwable) {
super(message, throwable);
}
}

View File

@@ -40,109 +40,109 @@ import org.springframework.util.Assert;
*/
public class DomContentHandler implements ContentHandler {
private final Document document;
private final Document document;
private final List<Element> elements = new ArrayList<Element>();
private final List<Element> elements = new ArrayList<Element>();
private final Node node;
private final Node node;
/**
* Creates a new instance of the {@code DomContentHandler} with the given node.
*
* @param node the node to publish events to
*/
public DomContentHandler(Node node) {
Assert.notNull(node, "node must not be null");
this.node = node;
if (node instanceof Document) {
document = (Document) node;
}
else {
document = node.getOwnerDocument();
}
Assert.notNull(document, "document must not be null");
}
/**
* Creates a new instance of the {@code DomContentHandler} with the given node.
*
* @param node the node to publish events to
*/
public DomContentHandler(Node node) {
Assert.notNull(node, "node must not be null");
this.node = node;
if (node instanceof Document) {
document = (Document) node;
}
else {
document = node.getOwnerDocument();
}
Assert.notNull(document, "document must not be null");
}
private Node getParent() {
if (!elements.isEmpty()) {
return elements.get(elements.size() - 1);
}
else {
return node;
}
}
private Node getParent() {
if (!elements.isEmpty()) {
return elements.get(elements.size() - 1);
}
else {
return node;
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Node parent = getParent();
Element element = document.createElementNS(uri, qName);
for (int i = 0; i < attributes.getLength(); i++) {
String attrUri = attributes.getURI(i);
String attrQname = attributes.getQName(i);
String value = attributes.getValue(i);
if (!attrQname.startsWith("xmlns")) {
element.setAttributeNS(attrUri, attrQname, value);
}
}
element = (Element) parent.appendChild(element);
elements.add(element);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Node parent = getParent();
Element element = document.createElementNS(uri, qName);
for (int i = 0; i < attributes.getLength(); i++) {
String attrUri = attributes.getURI(i);
String attrQname = attributes.getQName(i);
String value = attributes.getValue(i);
if (!attrQname.startsWith("xmlns")) {
element.setAttributeNS(attrUri, attrQname, value);
}
}
element = (Element) parent.appendChild(element);
elements.add(element);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
elements.remove(elements.size() - 1);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
elements.remove(elements.size() - 1);
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
String data = new String(ch, start, length);
Node parent = getParent();
Node lastChild = parent.getLastChild();
if (lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) {
((Text) lastChild).appendData(data);
}
else {
Text text = document.createTextNode(data);
parent.appendChild(text);
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
String data = new String(ch, start, length);
Node parent = getParent();
Node lastChild = parent.getLastChild();
if (lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) {
((Text) lastChild).appendData(data);
}
else {
Text text = document.createTextNode(data);
parent.appendChild(text);
}
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
Node parent = getParent();
ProcessingInstruction pi = document.createProcessingInstruction(target, data);
parent.appendChild(pi);
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
Node parent = getParent();
ProcessingInstruction pi = document.createProcessingInstruction(target, data);
parent.appendChild(pi);
}
/*
* Unsupported
*/
/*
* Unsupported
*/
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
}
@Override
public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
}

View File

@@ -47,29 +47,29 @@ import org.springframework.util.StringUtils;
*/
public class QNameEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(QNameUtils.parseQNameString(text));
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(QNameUtils.parseQNameString(text));
}
@Override
public String getAsText() {
Object value = getValue();
if (value == null || !(value instanceof QName)) {
return "";
}
else {
QName qName = (QName) value;
String prefix = qName.getPrefix();
if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(prefix)) {
return "{" + qName.getNamespaceURI() + "}" + prefix + ":" + qName.getLocalPart();
}
else if (StringUtils.hasLength(qName.getNamespaceURI())) {
return "{" + qName.getNamespaceURI() + "}" + qName.getLocalPart();
}
else {
return qName.getLocalPart();
}
}
}
@Override
public String getAsText() {
Object value = getValue();
if (value == null || !(value instanceof QName)) {
return "";
}
else {
QName qName = (QName) value;
String prefix = qName.getPrefix();
if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(prefix)) {
return "{" + qName.getNamespaceURI() + "}" + prefix + ":" + qName.getLocalPart();
}
else if (StringUtils.hasLength(qName.getNamespaceURI())) {
return "{" + qName.getNamespaceURI() + "}" + qName.getLocalPart();
}
else {
return qName.getLocalPart();
}
}
}
}

View File

@@ -33,147 +33,147 @@ import org.springframework.util.StringUtils;
public abstract class QNameUtils {
/**
* Creates a new {@code QName} with the given parameters. Sets the prefix if possible, i.e. if the
* {@code QName(String, String, String)} constructor can be found. If this constructor is not available (as is
* the case on older implementations of JAX-RPC), the prefix is ignored.
*
* @param namespaceUri namespace URI of the {@code QName}
* @param localPart local part of the {@code QName}
* @param prefix prefix of the {@code QName}. May be ignored.
* @return the created {@code QName}
* @see QName#QName(String,String,String)
* Creates a new {@code QName} with the given parameters. Sets the prefix if possible, i.e. if the
* {@code QName(String, String, String)} constructor can be found. If this constructor is not available (as is
* the case on older implementations of JAX-RPC), the prefix is ignored.
*
* @param namespaceUri namespace URI of the {@code QName}
* @param localPart local part of the {@code QName}
* @param prefix prefix of the {@code QName}. May be ignored.
* @return the created {@code QName}
* @see QName#QName(String,String,String)
* @deprecated in favor of {@link QName#QName(String, String, String)}
*/
@Deprecated
public static QName createQName(String namespaceUri, String localPart, String prefix) {
return new QName(namespaceUri, localPart, prefix);
}
*/
@Deprecated
public static QName createQName(String namespaceUri, String localPart, String prefix) {
return new QName(namespaceUri, localPart, prefix);
}
/**
* Returns the prefix of the given {@code QName}. Returns the prefix if available, i.e. if the
* {@code QName.getPrefix()} method can be found. If this method is not available (as is the case on older
* implementations of JAX-RPC), an empty string is returned.
*
* @param qName the {@code QName} to return the prefix from
* @return the prefix, if available, or an empty string
* @see javax.xml.namespace.QName#getPrefix()
* @deprecated in favor of {@link QName#getPrefix()}
*/
@Deprecated
public static String getPrefix(QName qName) {
return qName.getPrefix();
}
/**
* Returns the prefix of the given {@code QName}. Returns the prefix if available, i.e. if the
* {@code QName.getPrefix()} method can be found. If this method is not available (as is the case on older
* implementations of JAX-RPC), an empty string is returned.
*
* @param qName the {@code QName} to return the prefix from
* @return the prefix, if available, or an empty string
* @see javax.xml.namespace.QName#getPrefix()
* @deprecated in favor of {@link QName#getPrefix()}
*/
@Deprecated
public static String getPrefix(QName qName) {
return qName.getPrefix();
}
/**
* Validates the given String as a QName
*
* @param text the qualified name
* @return {@code true} if valid, {@code false} otherwise
*/
public static boolean validateQName(String text) {
if (!StringUtils.hasLength(text)) {
return false;
}
if (text.charAt(0) == '{') {
int i = text.indexOf('}');
/**
* Validates the given String as a QName
*
* @param text the qualified name
* @return {@code true} if valid, {@code false} otherwise
*/
public static boolean validateQName(String text) {
if (!StringUtils.hasLength(text)) {
return false;
}
if (text.charAt(0) == '{') {
int i = text.indexOf('}');
if (i == -1 || i == text.length() - 1) {
return false;
}
}
return true;
}
if (i == -1 || i == text.length() - 1) {
return false;
}
}
return true;
}
/**
* Returns the qualified name of the given DOM Node.
*
* @param node the node
* @return the qualified name of the node
*/
public static QName getQNameForNode(Node node) {
if (node.getNamespaceURI() != null && node.getPrefix() != null && node.getLocalName() != null) {
return new QName(node.getNamespaceURI(), node.getLocalName(),
node.getPrefix());
}
else if (node.getNamespaceURI() != null && node.getLocalName() != null) {
return new QName(node.getNamespaceURI(), node.getLocalName());
}
else if (node.getLocalName() != null) {
return new QName(node.getLocalName());
}
else {
// as a last resort, use the node name
return new QName(node.getNodeName());
}
}
/**
* Returns the qualified name of the given DOM Node.
*
* @param node the node
* @return the qualified name of the node
*/
public static QName getQNameForNode(Node node) {
if (node.getNamespaceURI() != null && node.getPrefix() != null && node.getLocalName() != null) {
return new QName(node.getNamespaceURI(), node.getLocalName(),
node.getPrefix());
}
else if (node.getNamespaceURI() != null && node.getLocalName() != null) {
return new QName(node.getNamespaceURI(), node.getLocalName());
}
else if (node.getLocalName() != null) {
return new QName(node.getLocalName());
}
else {
// as a last resort, use the node name
return new QName(node.getNodeName());
}
}
/**
* Convert a {@code QName} to a qualified name, as used by DOM and SAX. The returned string has a format of
* {@code prefix:localName} if the prefix is set, or just {@code localName} if not.
*
* @param qName the {@code QName}
* @return the qualified name
*/
public static String toQualifiedName(QName qName) {
String prefix = qName.getPrefix();
if (!StringUtils.hasLength(prefix)) {
return qName.getLocalPart();
}
else {
return prefix + ":" + qName.getLocalPart();
}
}
/**
* Convert a {@code QName} to a qualified name, as used by DOM and SAX. The returned string has a format of
* {@code prefix:localName} if the prefix is set, or just {@code localName} if not.
*
* @param qName the {@code QName}
* @return the qualified name
*/
public static String toQualifiedName(QName qName) {
String prefix = qName.getPrefix();
if (!StringUtils.hasLength(prefix)) {
return qName.getLocalPart();
}
else {
return prefix + ":" + qName.getLocalPart();
}
}
/**
* Convert a namespace URI and DOM or SAX qualified name to a {@code QName}. The qualified name can have the
* form {@code prefix:localname} or {@code localName}.
*
* @param namespaceUri the namespace URI
* @param qualifiedName the qualified name
* @return a QName
*/
public static QName toQName(String namespaceUri, String qualifiedName) {
int idx = qualifiedName.indexOf(':');
if (idx == -1) {
return new QName(namespaceUri, qualifiedName);
}
else {
return new QName(namespaceUri, qualifiedName.substring(idx + 1),
qualifiedName.substring(0, idx));
}
}
/**
* Convert a namespace URI and DOM or SAX qualified name to a {@code QName}. The qualified name can have the
* form {@code prefix:localname} or {@code localName}.
*
* @param namespaceUri the namespace URI
* @param qualifiedName the qualified name
* @return a QName
*/
public static QName toQName(String namespaceUri, String qualifiedName) {
int idx = qualifiedName.indexOf(':');
if (idx == -1) {
return new QName(namespaceUri, qualifiedName);
}
else {
return new QName(namespaceUri, qualifiedName.substring(idx + 1),
qualifiedName.substring(0, idx));
}
}
/**
* Parse the given qualified name string into a {@code QName}. Expects the syntax {@code localPart},
* {@code{namespace}localPart}, or {@code{namespace}prefix:localPart}. This format resembles the
* {@code toString()} representation of {@code QName} itself, but allows for prefixes to be specified as
* well.
*
* @return a corresponding QName instance
* @throws IllegalArgumentException when the given string is {@code null} or empty.
*/
public static QName parseQNameString(String qNameString) {
Assert.hasLength(qNameString, "QName text may not be null or empty");
if (qNameString.charAt(0) != '{') {
return new QName(qNameString);
}
else {
int endOfNamespaceURI = qNameString.indexOf('}');
if (endOfNamespaceURI == -1) {
throw new IllegalArgumentException(
"Cannot create QName from \"" + qNameString + "\", missing closing \"}\"");
}
int prefixSeperator = qNameString.indexOf(':', endOfNamespaceURI + 1);
String namespaceURI = qNameString.substring(1, endOfNamespaceURI);
if (prefixSeperator == -1) {
return new QName(namespaceURI, qNameString.substring(endOfNamespaceURI + 1));
}
else {
return new QName(namespaceURI, qNameString.substring(prefixSeperator + 1),
qNameString.substring(endOfNamespaceURI + 1, prefixSeperator));
}
}
/**
* Parse the given qualified name string into a {@code QName}. Expects the syntax {@code localPart},
* {@code{namespace}localPart}, or {@code{namespace}prefix:localPart}. This format resembles the
* {@code toString()} representation of {@code QName} itself, but allows for prefixes to be specified as
* well.
*
* @return a corresponding QName instance
* @throws IllegalArgumentException when the given string is {@code null} or empty.
*/
public static QName parseQNameString(String qNameString) {
Assert.hasLength(qNameString, "QName text may not be null or empty");
if (qNameString.charAt(0) != '{') {
return new QName(qNameString);
}
else {
int endOfNamespaceURI = qNameString.indexOf('}');
if (endOfNamespaceURI == -1) {
throw new IllegalArgumentException(
"Cannot create QName from \"" + qNameString + "\", missing closing \"}\"");
}
int prefixSeperator = qNameString.indexOf(':', endOfNamespaceURI + 1);
String namespaceURI = qNameString.substring(1, endOfNamespaceURI);
if (prefixSeperator == -1) {
return new QName(namespaceURI, qNameString.substring(endOfNamespaceURI + 1));
}
else {
return new QName(namespaceURI, qNameString.substring(prefixSeperator + 1),
qNameString.substring(endOfNamespaceURI + 1, prefixSeperator));
}
}
}
}
}

View File

@@ -38,130 +38,130 @@ import org.springframework.util.Assert;
*/
public class SimpleNamespaceContext implements NamespaceContext {
private Map<String, String> prefixToNamespaceUri = new LinkedHashMap<String, String>();
private Map<String, String> prefixToNamespaceUri = new LinkedHashMap<String, String>();
private Map<String, Set<String>> namespaceUriToPrefixes = new LinkedHashMap<String, Set<String>>();
private Map<String, Set<String>> namespaceUriToPrefixes = new LinkedHashMap<String, Set<String>>();
@Override
public String getNamespaceURI(String prefix) {
Assert.notNull(prefix, "prefix is null");
if (XMLConstants.XML_NS_PREFIX.equals(prefix)) {
return XMLConstants.XML_NS_URI;
}
else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) {
return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
}
else if (prefixToNamespaceUri.containsKey(prefix)) {
return prefixToNamespaceUri.get(prefix);
}
return XMLConstants.NULL_NS_URI;
}
@Override
public String getNamespaceURI(String prefix) {
Assert.notNull(prefix, "prefix is null");
if (XMLConstants.XML_NS_PREFIX.equals(prefix)) {
return XMLConstants.XML_NS_URI;
}
else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) {
return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
}
else if (prefixToNamespaceUri.containsKey(prefix)) {
return prefixToNamespaceUri.get(prefix);
}
return XMLConstants.NULL_NS_URI;
}
@Override
public String getPrefix(String namespaceUri) {
Iterator<String> iterator = getPrefixes(namespaceUri);
return iterator.hasNext() ? iterator.next() : null;
}
@Override
public String getPrefix(String namespaceUri) {
Iterator<String> iterator = getPrefixes(namespaceUri);
return iterator.hasNext() ? iterator.next() : null;
}
@Override
public Iterator<String> getPrefixes(String namespaceUri) {
Set<String> prefixes = getPrefixesInternal(namespaceUri);
prefixes = Collections.unmodifiableSet(prefixes);
return prefixes.iterator();
}
@Override
public Iterator<String> getPrefixes(String namespaceUri) {
Set<String> prefixes = getPrefixesInternal(namespaceUri);
prefixes = Collections.unmodifiableSet(prefixes);
return prefixes.iterator();
}
/**
* Sets the bindings for this namespace context. The supplied map must consist of string key value pairs.
*
* @param bindings the bindings
*/
public void setBindings(Map<String, String> bindings) {
for (Map.Entry<String, String> entry : bindings.entrySet()) {
bindNamespaceUri(entry.getKey(), entry.getValue());
}
}
/**
* Sets the bindings for this namespace context. The supplied map must consist of string key value pairs.
*
* @param bindings the bindings
*/
public void setBindings(Map<String, String> bindings) {
for (Map.Entry<String, String> entry : bindings.entrySet()) {
bindNamespaceUri(entry.getKey(), entry.getValue());
}
}
/**
* Binds the given namespace as default namespace.
*
* @param namespaceUri the namespace uri
*/
public void bindDefaultNamespaceUri(String namespaceUri) {
bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, namespaceUri);
}
/**
* Binds the given namespace as default namespace.
*
* @param namespaceUri the namespace uri
*/
public void bindDefaultNamespaceUri(String namespaceUri) {
bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, namespaceUri);
}
/**
* Binds the given prefix to the given namespace.
*
* @param prefix the namespace prefix
* @param namespaceUri the namespace uri
*/
public void bindNamespaceUri(String prefix, String namespaceUri) {
Assert.notNull(prefix, "No prefix given");
Assert.notNull(namespaceUri, "No namespaceUri given");
if (XMLConstants.XML_NS_PREFIX.equals(prefix)) {
Assert.isTrue(XMLConstants.XML_NS_URI.equals(namespaceUri), "Prefix \"" + prefix +
"\" bound to namespace \"" + namespaceUri + "\" (should be \"" + XMLConstants.XML_NS_URI + "\")");
} else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) {
Assert.isTrue(XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri), "Prefix \"" + prefix +
"\" bound to namespace \"" + namespaceUri + "\" (should be \"" +
XMLConstants.XMLNS_ATTRIBUTE_NS_URI + "\")");
}
else {
prefixToNamespaceUri.put(prefix, namespaceUri);
getPrefixesInternal(namespaceUri).add(prefix);
}
}
/**
* Binds the given prefix to the given namespace.
*
* @param prefix the namespace prefix
* @param namespaceUri the namespace uri
*/
public void bindNamespaceUri(String prefix, String namespaceUri) {
Assert.notNull(prefix, "No prefix given");
Assert.notNull(namespaceUri, "No namespaceUri given");
if (XMLConstants.XML_NS_PREFIX.equals(prefix)) {
Assert.isTrue(XMLConstants.XML_NS_URI.equals(namespaceUri), "Prefix \"" + prefix +
"\" bound to namespace \"" + namespaceUri + "\" (should be \"" + XMLConstants.XML_NS_URI + "\")");
} else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) {
Assert.isTrue(XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri), "Prefix \"" + prefix +
"\" bound to namespace \"" + namespaceUri + "\" (should be \"" +
XMLConstants.XMLNS_ATTRIBUTE_NS_URI + "\")");
}
else {
prefixToNamespaceUri.put(prefix, namespaceUri);
getPrefixesInternal(namespaceUri).add(prefix);
}
}
/** Removes all declared prefixes. */
public void clear() {
prefixToNamespaceUri.clear();
namespaceUriToPrefixes.clear();
}
/** Removes all declared prefixes. */
public void clear() {
prefixToNamespaceUri.clear();
namespaceUriToPrefixes.clear();
}
/**
* Returns all declared prefixes.
*
* @return the declared prefixes
*/
public Iterator<String> getBoundPrefixes() {
Set<String> prefixes = new HashSet<String>(prefixToNamespaceUri.keySet());
prefixes.remove(XMLConstants.DEFAULT_NS_PREFIX);
prefixes = Collections.unmodifiableSet(prefixes);
return prefixes.iterator();
}
/**
* Returns all declared prefixes.
*
* @return the declared prefixes
*/
public Iterator<String> getBoundPrefixes() {
Set<String> prefixes = new HashSet<String>(prefixToNamespaceUri.keySet());
prefixes.remove(XMLConstants.DEFAULT_NS_PREFIX);
prefixes = Collections.unmodifiableSet(prefixes);
return prefixes.iterator();
}
private Set<String> getPrefixesInternal(String namespaceUri) {
if (XMLConstants.XML_NS_URI.equals(namespaceUri)) {
return Collections.singleton(XMLConstants.XML_NS_PREFIX);
}
else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) {
return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE);
}
else {
Set<String> set = namespaceUriToPrefixes.get(namespaceUri);
if (set == null) {
set = new LinkedHashSet<String>();
namespaceUriToPrefixes.put(namespaceUri, set);
}
return set;
}
}
private Set<String> getPrefixesInternal(String namespaceUri) {
if (XMLConstants.XML_NS_URI.equals(namespaceUri)) {
return Collections.singleton(XMLConstants.XML_NS_PREFIX);
}
else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) {
return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE);
}
else {
Set<String> set = namespaceUriToPrefixes.get(namespaceUri);
if (set == null) {
set = new LinkedHashSet<String>();
namespaceUriToPrefixes.put(namespaceUri, set);
}
return set;
}
}
/**
* Removes the given prefix from this context.
*
* @param prefix the prefix to be removed
*/
public void removeBinding(String prefix) {
String namespaceUri = prefixToNamespaceUri.remove(prefix);
if (namespaceUri != null) {
Set<String> prefixes = getPrefixesInternal(namespaceUri);
prefixes.remove(prefix);
}
}
/**
* Removes the given prefix from this context.
*
* @param prefix the prefix to be removed
*/
public void removeBinding(String prefix) {
String namespaceUri = prefixToNamespaceUri.remove(prefix);
if (namespaceUri != null) {
Set<String> prefixes = getPrefixesInternal(namespaceUri);
prefixes.remove(prefix);
}
}
public boolean hasBinding(String prefix) {
return prefixToNamespaceUri.containsKey(prefix);
}
public boolean hasBinding(String prefix) {
return prefixToNamespaceUri.containsKey(prefix);
}
}

View File

@@ -38,106 +38,106 @@ import org.xml.sax.ext.LexicalHandler;
*/
public abstract class AbstractXmlReader implements XMLReader {
private DTDHandler dtdHandler;
private DTDHandler dtdHandler;
private ContentHandler contentHandler;
private ContentHandler contentHandler;
private EntityResolver entityResolver;
private EntityResolver entityResolver;
private ErrorHandler errorHandler;
private ErrorHandler errorHandler;
private LexicalHandler lexicalHandler;
private LexicalHandler lexicalHandler;
@Override
public ContentHandler getContentHandler() {
return contentHandler;
}
@Override
public ContentHandler getContentHandler() {
return contentHandler;
}
@Override
public void setContentHandler(ContentHandler contentHandler) {
this.contentHandler = contentHandler;
}
@Override
public void setContentHandler(ContentHandler contentHandler) {
this.contentHandler = contentHandler;
}
@Override
public void setDTDHandler(DTDHandler dtdHandler) {
this.dtdHandler = dtdHandler;
}
@Override
public void setDTDHandler(DTDHandler dtdHandler) {
this.dtdHandler = dtdHandler;
}
@Override
public DTDHandler getDTDHandler() {
return dtdHandler;
}
@Override
public DTDHandler getDTDHandler() {
return dtdHandler;
}
@Override
public EntityResolver getEntityResolver() {
return entityResolver;
}
@Override
public EntityResolver getEntityResolver() {
return entityResolver;
}
@Override
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
@Override
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
@Override
public ErrorHandler getErrorHandler() {
return errorHandler;
}
@Override
public ErrorHandler getErrorHandler() {
return errorHandler;
}
@Override
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
@Override
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
protected LexicalHandler getLexicalHandler() {
return lexicalHandler;
}
protected LexicalHandler getLexicalHandler() {
return lexicalHandler;
}
/**
* Throws a {@code SAXNotRecognizedException} exception.
*
* @throws org.xml.sax.SAXNotRecognizedException
* always
*/
@Override
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
throw new SAXNotRecognizedException(name);
}
/**
* Throws a {@code SAXNotRecognizedException} exception.
*
* @throws org.xml.sax.SAXNotRecognizedException
* always
*/
@Override
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
throw new SAXNotRecognizedException(name);
}
/**
* Throws a {@code SAXNotRecognizedException} exception.
*
* @throws SAXNotRecognizedException always
*/
@Override
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
throw new SAXNotRecognizedException(name);
}
/**
* Throws a {@code SAXNotRecognizedException} exception.
*
* @throws SAXNotRecognizedException always
*/
@Override
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
throw new SAXNotRecognizedException(name);
}
/**
* Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical
* handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}.
*/
@Override
public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
return lexicalHandler;
}
else {
throw new SAXNotRecognizedException(name);
}
}
/**
* Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical
* handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}.
*/
@Override
public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
return lexicalHandler;
}
else {
throw new SAXNotRecognizedException(name);
}
}
/**
* Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical
* handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}.
*/
@Override
public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
lexicalHandler = (LexicalHandler) value;
}
else {
throw new SAXNotRecognizedException(name);
}
}
/**
* Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical
* handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}.
*/
@Override
public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
lexicalHandler = (LexicalHandler) value;
}
else {
throw new SAXNotRecognizedException(name);
}
}
}

View File

@@ -34,37 +34,37 @@ import org.xml.sax.InputSource;
*/
public abstract class SaxUtils {
private static final Log logger = LogFactory.getLog(SaxUtils.class);
private static final Log logger = LogFactory.getLog(SaxUtils.class);
/**
* Creates a SAX {@code InputSource} from the given resource. Sets the system identifier to the resource's
* {@code URL}, if available.
*
* @param resource the resource
* @return the input source created from the resource
* @throws IOException if an I/O exception occurs
* @see InputSource#setSystemId(String)
* @see #getSystemId(org.springframework.core.io.Resource)
*/
public static InputSource createInputSource(Resource resource) throws IOException {
InputSource inputSource = new InputSource(resource.getInputStream());
inputSource.setSystemId(getSystemId(resource));
return inputSource;
}
/**
* Creates a SAX {@code InputSource} from the given resource. Sets the system identifier to the resource's
* {@code URL}, if available.
*
* @param resource the resource
* @return the input source created from the resource
* @throws IOException if an I/O exception occurs
* @see InputSource#setSystemId(String)
* @see #getSystemId(org.springframework.core.io.Resource)
*/
public static InputSource createInputSource(Resource resource) throws IOException {
InputSource inputSource = new InputSource(resource.getInputStream());
inputSource.setSystemId(getSystemId(resource));
return inputSource;
}
/** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */
public static String getSystemId(Resource resource) {
try {
return new URI(resource.getURL().toExternalForm()).toString();
}
catch (IOException ex) {
logger.debug("Could not get System ID from [" + resource + "], ex");
return null;
}
catch (URISyntaxException e) {
logger.debug("Could not get System ID from [" + resource + "], ex");
return null;
}
}
/** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */
public static String getSystemId(Resource resource) {
try {
return new URI(resource.getURL().toExternalForm()).toString();
}
catch (IOException ex) {
logger.debug("Could not get System ID from [" + resource + "], ex");
return null;
}
catch (URISyntaxException e) {
logger.debug("Could not get System ID from [" + resource + "], ex");
return null;
}
}
}

View File

@@ -33,21 +33,21 @@ import org.xml.sax.XMLReader;
*/
public class ResourceSource extends SAXSource {
/**
* Initializes a new instance of the {@code ResourceSource} with the given resource.
*
* @param content the content
*/
public ResourceSource(Resource content) throws IOException {
super(SaxUtils.createInputSource(content));
}
/**
* Initializes a new instance of the {@code ResourceSource} with the given resource.
*
* @param content the content
*/
public ResourceSource(Resource content) throws IOException {
super(SaxUtils.createInputSource(content));
}
/**
* Initializes a new instance of the {@code ResourceSource} with the given {@link XMLReader} and resource.
*
* @param content the content
*/
public ResourceSource(XMLReader reader, Resource content) throws IOException {
super(reader, SaxUtils.createInputSource(content));
}
/**
* Initializes a new instance of the {@code ResourceSource} with the given {@link XMLReader} and resource.
*
* @param content the content
*/
public ResourceSource(XMLReader reader, Resource content) throws IOException {
super(reader, SaxUtils.createInputSource(content));
}
}

View File

@@ -29,13 +29,13 @@ import javax.xml.transform.stream.StreamResult;
*/
public class StringResult extends StreamResult {
public StringResult() {
super(new StringWriter());
}
public StringResult() {
super(new StringWriter());
}
/** Returns the written XML as a string. */
public String toString() {
return getWriter().toString();
}
/** Returns the written XML as a string. */
public String toString() {
return getWriter().toString();
}
}

View File

@@ -32,55 +32,55 @@ import org.springframework.util.Assert;
*/
public class StringSource extends StreamSource {
private final String content;
private final String content;
/**
* Initializes a new instance of the {@code StringSource} with the given string content.
*
* @param content the content
*/
public StringSource(String content) {
Assert.notNull(content, "'content' must not be null");
this.content = content;
}
/**
* Initializes a new instance of the {@code StringSource} with the given string content.
*
* @param content the content
*/
public StringSource(String content) {
Assert.notNull(content, "'content' must not be null");
this.content = content;
}
@Override
public Reader getReader() {
return new StringReader(content);
}
@Override
public Reader getReader() {
return new StringReader(content);
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setInputStream(InputStream inputStream) {
throw new UnsupportedOperationException("setInputStream is not supported");
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setInputStream(InputStream inputStream) {
throw new UnsupportedOperationException("setInputStream is not supported");
}
/**
* Returns {@code null}.
*
* @return {@code null}
*/
@Override
public InputStream getInputStream() {
return null;
}
/**
* Returns {@code null}.
*
* @return {@code null}
*/
@Override
public InputStream getInputStream() {
return null;
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setReader(Reader reader) {
throw new UnsupportedOperationException("setReader is not supported");
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setReader(Reader reader) {
throw new UnsupportedOperationException("setReader is not supported");
}
@Override
public String toString() {
return content;
}
@Override
public String toString() {
return content;
}
}

View File

@@ -35,107 +35,107 @@ import org.springframework.util.Assert;
*/
public class TransformerHelper {
private volatile TransformerFactory transformerFactory;
private volatile TransformerFactory transformerFactory;
private Class<? extends TransformerFactory> transformerFactoryClass;
private Class<? extends TransformerFactory> transformerFactoryClass;
/**
* Initializes a new instance of the {@code TransformerHelper}.
*/
public TransformerHelper() {
}
/**
* Initializes a new instance of the {@code TransformerHelper}.
*/
public TransformerHelper() {
}
/**
* Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory}.
*/
public TransformerHelper(TransformerFactory transformerFactory) {
this.transformerFactory = transformerFactory;
}
/**
* Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory}.
*/
public TransformerHelper(TransformerFactory transformerFactory) {
this.transformerFactory = transformerFactory;
}
/**
* Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory} class.
*/
public TransformerHelper(Class<? extends TransformerFactory> transformerFactoryClass) {
setTransformerFactoryClass(transformerFactoryClass);
}
/**
* Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory} class.
*/
public TransformerHelper(Class<? extends TransformerFactory> transformerFactoryClass) {
setTransformerFactoryClass(transformerFactoryClass);
}
/**
* Specify the {@code TransformerFactory} class to use.
*/
public void setTransformerFactoryClass(Class<? extends TransformerFactory> transformerFactoryClass) {
Assert.isAssignable(TransformerFactory.class, transformerFactoryClass);
this.transformerFactoryClass = transformerFactoryClass;
}
/**
* Specify the {@code TransformerFactory} class to use.
*/
public void setTransformerFactoryClass(Class<? extends TransformerFactory> transformerFactoryClass) {
Assert.isAssignable(TransformerFactory.class, transformerFactoryClass);
this.transformerFactoryClass = transformerFactoryClass;
}
/**
* Instantiate a new TransformerFactory.
*
* <p>The default implementation simply calls {@link TransformerFactory#newInstance()}. If a {@link
* #setTransformerFactoryClass transformerFactoryClass} has been specified explicitly, the default constructor of
* the specified class will be called instead.
*
* <p>Can be overridden in subclasses.
*
* @param transformerFactoryClass the specified factory class (if any)
* @return the new TransactionFactory instance
* @see #setTransformerFactoryClass
* @see #getTransformerFactory()
*/
protected TransformerFactory newTransformerFactory(Class<? extends TransformerFactory> transformerFactoryClass) {
if (transformerFactoryClass != null) {
try {
return transformerFactoryClass.newInstance();
}
catch (Exception ex) {
throw new TransformerFactoryConfigurationError(ex,
"Could not instantiate TransformerFactory [" + transformerFactoryClass + "]");
}
}
else {
return TransformerFactory.newInstance();
}
}
/**
* Instantiate a new TransformerFactory.
*
* <p>The default implementation simply calls {@link TransformerFactory#newInstance()}. If a {@link
* #setTransformerFactoryClass transformerFactoryClass} has been specified explicitly, the default constructor of
* the specified class will be called instead.
*
* <p>Can be overridden in subclasses.
*
* @param transformerFactoryClass the specified factory class (if any)
* @return the new TransactionFactory instance
* @see #setTransformerFactoryClass
* @see #getTransformerFactory()
*/
protected TransformerFactory newTransformerFactory(Class<? extends TransformerFactory> transformerFactoryClass) {
if (transformerFactoryClass != null) {
try {
return transformerFactoryClass.newInstance();
}
catch (Exception ex) {
throw new TransformerFactoryConfigurationError(ex,
"Could not instantiate TransformerFactory [" + transformerFactoryClass + "]");
}
}
else {
return TransformerFactory.newInstance();
}
}
/**
* Returns the {@code TransformerFactory}.
*
* @return the transformer factory
*/
public TransformerFactory getTransformerFactory() {
TransformerFactory result = transformerFactory;
if (result == null) {
synchronized (this) {
result = transformerFactory;
if (result == null) {
transformerFactory = result = newTransformerFactory(transformerFactoryClass);
}
}
}
return result;
}
/**
* Returns the {@code TransformerFactory}.
*
* @return the transformer factory
*/
public TransformerFactory getTransformerFactory() {
TransformerFactory result = transformerFactory;
if (result == null) {
synchronized (this) {
result = transformerFactory;
if (result == null) {
transformerFactory = result = newTransformerFactory(transformerFactoryClass);
}
}
}
return result;
}
/**
* Creates a new {@code Transformer}. Must be called per thread, as transformers are not thread-safe.
*
* @return the created transformer
* @throws TransformerConfigurationException
* if thrown by JAXP methods
*/
public Transformer createTransformer() throws TransformerConfigurationException {
return getTransformerFactory().newTransformer();
}
/**
* Creates a new {@code Transformer}. Must be called per thread, as transformers are not thread-safe.
*
* @return the created transformer
* @throws TransformerConfigurationException
* if thrown by JAXP methods
*/
public Transformer createTransformer() throws TransformerConfigurationException {
return getTransformerFactory().newTransformer();
}
/**
* Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every
* call, as transformers are not thread-safe.
*
* @param source the source to transform from
* @param result the result to transform to
* @throws TransformerException if thrown by JAXP methods
*/
public void transform(Source source, Result result) throws TransformerException {
Transformer transformer = createTransformer();
transformer.transform(source, result);
}
/**
* Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every
* call, as transformers are not thread-safe.
*
* @param source the source to transform from
* @param result the result to transform to
* @throws TransformerException if thrown by JAXP methods
*/
public void transform(Source source, Result result) throws TransformerException {
Transformer transformer = createTransformer();
transformer.transform(source, result);
}
}

View File

@@ -37,63 +37,63 @@ import org.apache.commons.logging.LogFactory;
*/
public abstract class TransformerObjectSupport {
/**
* Logger available to subclasses.
*/
protected final Log logger = LogFactory.getLog(getClass());
/**
* Logger available to subclasses.
*/
protected final Log logger = LogFactory.getLog(getClass());
private TransformerHelper transformerHelper = new TransformerHelper();
private TransformerHelper transformerHelper = new TransformerHelper();
/**
* Specify the {@code TransformerFactory} class to use.
*/
public void setTransformerFactoryClass(Class<? extends TransformerFactory> transformerFactoryClass) {
transformerHelper.setTransformerFactoryClass(transformerFactoryClass);
}
/**
* Specify the {@code TransformerFactory} class to use.
*/
public void setTransformerFactoryClass(Class<? extends TransformerFactory> transformerFactoryClass) {
transformerHelper.setTransformerFactoryClass(transformerFactoryClass);
}
/**
* Instantiate a new TransformerFactory. <p>The default implementation simply calls {@link
* TransformerFactory#newInstance()}. If a {@link #setTransformerFactoryClass "transformerFactoryClass"} has been
* specified explicitly, the default constructor of the specified class will be called instead. <p>Can be overridden
* in subclasses.
*
* @param transformerFactoryClass the specified factory class (if any)
* @return the new TransactionFactory instance
* @see #setTransformerFactoryClass
* @see #getTransformerFactory()
*/
protected TransformerFactory newTransformerFactory(Class<? extends TransformerFactory> transformerFactoryClass) {
return transformerHelper.newTransformerFactory(transformerFactoryClass);
}
/**
* Instantiate a new TransformerFactory. <p>The default implementation simply calls {@link
* TransformerFactory#newInstance()}. If a {@link #setTransformerFactoryClass "transformerFactoryClass"} has been
* specified explicitly, the default constructor of the specified class will be called instead. <p>Can be overridden
* in subclasses.
*
* @param transformerFactoryClass the specified factory class (if any)
* @return the new TransactionFactory instance
* @see #setTransformerFactoryClass
* @see #getTransformerFactory()
*/
protected TransformerFactory newTransformerFactory(Class<? extends TransformerFactory> transformerFactoryClass) {
return transformerHelper.newTransformerFactory(transformerFactoryClass);
}
/**
* Returns the {@code TransformerFactory}.
*/
protected TransformerFactory getTransformerFactory() {
return transformerHelper.getTransformerFactory();
}
/**
* Returns the {@code TransformerFactory}.
*/
protected TransformerFactory getTransformerFactory() {
return transformerHelper.getTransformerFactory();
}
/**
* Creates a new {@code Transformer}. Must be called per request, as transformers are not thread-safe.
*
* @return the created transformer
* @throws TransformerConfigurationException
* if thrown by JAXP methods
*/
protected final Transformer createTransformer() throws TransformerConfigurationException {
return transformerHelper.createTransformer();
}
/**
* Creates a new {@code Transformer}. Must be called per request, as transformers are not thread-safe.
*
* @return the created transformer
* @throws TransformerConfigurationException
* if thrown by JAXP methods
*/
protected final Transformer createTransformer() throws TransformerConfigurationException {
return transformerHelper.createTransformer();
}
/**
* Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every
* call, as transformers are not thread-safe.
*
* @param source the source to transform from
* @param result the result to transform to
* @throws TransformerException if thrown by JAXP methods
*/
protected final void transform(Source source, Result result) throws TransformerException {
transformerHelper.transform(source, result);
}
/**
* Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every
* call, as transformers are not thread-safe.
*
* @param source the source to transform from
* @param result the result to transform to
* @throws TransformerException if thrown by JAXP methods
*/
protected final void transform(Source source, Result result) throws TransformerException {
transformerHelper.transform(source, result);
}
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -53,250 +53,250 @@ import org.xml.sax.ext.LexicalHandler;
*/
public abstract class TraxUtils {
/**
* Returns the {@link Document} of the given {@link DOMSource}.
*
* @param source the DOM source
* @return the document
*/
public static Document getDocument(DOMSource source) {
Node node = source.getNode();
if (node instanceof Document) {
return (Document) node;
}
else if (node != null) {
return node.getOwnerDocument();
}
else {
return null;
}
}
/**
* Returns the {@link Document} of the given {@link DOMSource}.
*
* @param source the DOM source
* @return the document
*/
public static Document getDocument(DOMSource source) {
Node node = source.getNode();
if (node instanceof Document) {
return (Document) node;
}
else if (node != null) {
return node.getOwnerDocument();
}
else {
return null;
}
}
/**
* Performs the given {@linkplain SourceCallback callback} operation on a {@link Source}. Supports both the JAXP 1.4
* {@link StAXSource} and the Spring 3.0 {@link StaxUtils#createStaxSource StaxSource}.
*
* @param source source to look at
* @param callback the callback to invoke for each kind of source
*/
public static void doWithSource(Source source, SourceCallback callback) throws Exception {
if (source instanceof DOMSource) {
callback.domSource(((DOMSource) source).getNode());
return;
}
else if (StaxUtils.isStaxSource(source)) {
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(source);
if (streamReader != null) {
callback.staxSource(streamReader);
return;
}
else {
XMLEventReader eventReader = StaxUtils.getXMLEventReader(source);
if (eventReader != null) {
callback.staxSource(eventReader);
return;
}
}
}
else if (source instanceof SAXSource) {
SAXSource saxSource = (SAXSource) source;
callback.saxSource(saxSource.getXMLReader(), saxSource.getInputSource());
return;
}
else if (source instanceof StreamSource) {
StreamSource streamSource = (StreamSource) source;
if (streamSource.getInputStream() != null) {
callback.streamSource(streamSource.getInputStream());
return;
}
else if (streamSource.getReader() != null) {
callback.streamSource(streamSource.getReader());
return;
}
}
if (StringUtils.hasLength(source.getSystemId())) {
String systemId = source.getSystemId();
callback.source(systemId);
}
else {
throw new IllegalArgumentException("Unknown Source type: " + source.getClass());
}
}
/**
* Performs the given {@linkplain SourceCallback callback} operation on a {@link Source}. Supports both the JAXP 1.4
* {@link StAXSource} and the Spring 3.0 {@link StaxUtils#createStaxSource StaxSource}.
*
* @param source source to look at
* @param callback the callback to invoke for each kind of source
*/
public static void doWithSource(Source source, SourceCallback callback) throws Exception {
if (source instanceof DOMSource) {
callback.domSource(((DOMSource) source).getNode());
return;
}
else if (StaxUtils.isStaxSource(source)) {
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(source);
if (streamReader != null) {
callback.staxSource(streamReader);
return;
}
else {
XMLEventReader eventReader = StaxUtils.getXMLEventReader(source);
if (eventReader != null) {
callback.staxSource(eventReader);
return;
}
}
}
else if (source instanceof SAXSource) {
SAXSource saxSource = (SAXSource) source;
callback.saxSource(saxSource.getXMLReader(), saxSource.getInputSource());
return;
}
else if (source instanceof StreamSource) {
StreamSource streamSource = (StreamSource) source;
if (streamSource.getInputStream() != null) {
callback.streamSource(streamSource.getInputStream());
return;
}
else if (streamSource.getReader() != null) {
callback.streamSource(streamSource.getReader());
return;
}
}
if (StringUtils.hasLength(source.getSystemId())) {
String systemId = source.getSystemId();
callback.source(systemId);
}
else {
throw new IllegalArgumentException("Unknown Source type: " + source.getClass());
}
}
/**
* Performs the given {@linkplain org.springframework.xml.transform.TraxUtils.ResultCallback callback} operation on a {@link javax.xml.transform.Result}. Supports both the JAXP 1.4
* {@link javax.xml.transform.stax.StAXResult} and the Spring 3.0 {@link org.springframework.util.xml.StaxUtils#createStaxResult StaxSource}.
*
* @param result result to look at
* @param callback the callback to invoke for each kind of result
*/
public static void doWithResult(Result result, ResultCallback callback) throws Exception {
if (result instanceof DOMResult) {
callback.domResult(((DOMResult) result).getNode());
return;
}
else if (StaxUtils.isStaxResult(result)) {
XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(result);
if (streamWriter != null) {
callback.staxResult(streamWriter);
return;
}
else {
XMLEventWriter eventWriter = StaxUtils.getXMLEventWriter(result);
if (eventWriter != null) {
callback.staxResult(eventWriter);
return;
}
}
}
else if (result instanceof SAXResult) {
SAXResult saxSource = (SAXResult) result;
callback.saxResult(saxSource.getHandler(), saxSource.getLexicalHandler());
return;
}
else if (result instanceof StreamResult) {
StreamResult streamSource = (StreamResult) result;
if (streamSource.getOutputStream() != null) {
callback.streamResult(streamSource.getOutputStream());
return;
}
else if (streamSource.getWriter() != null) {
callback.streamResult(streamSource.getWriter());
return;
}
}
if (StringUtils.hasLength(result.getSystemId())) {
String systemId = result.getSystemId();
callback.result(systemId);
}
else {
throw new IllegalArgumentException("Unknown Result type: " + result.getClass());
}
}
/**
* Performs the given {@linkplain org.springframework.xml.transform.TraxUtils.ResultCallback callback} operation on a {@link javax.xml.transform.Result}. Supports both the JAXP 1.4
* {@link javax.xml.transform.stax.StAXResult} and the Spring 3.0 {@link org.springframework.util.xml.StaxUtils#createStaxResult StaxSource}.
*
* @param result result to look at
* @param callback the callback to invoke for each kind of result
*/
public static void doWithResult(Result result, ResultCallback callback) throws Exception {
if (result instanceof DOMResult) {
callback.domResult(((DOMResult) result).getNode());
return;
}
else if (StaxUtils.isStaxResult(result)) {
XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(result);
if (streamWriter != null) {
callback.staxResult(streamWriter);
return;
}
else {
XMLEventWriter eventWriter = StaxUtils.getXMLEventWriter(result);
if (eventWriter != null) {
callback.staxResult(eventWriter);
return;
}
}
}
else if (result instanceof SAXResult) {
SAXResult saxSource = (SAXResult) result;
callback.saxResult(saxSource.getHandler(), saxSource.getLexicalHandler());
return;
}
else if (result instanceof StreamResult) {
StreamResult streamSource = (StreamResult) result;
if (streamSource.getOutputStream() != null) {
callback.streamResult(streamSource.getOutputStream());
return;
}
else if (streamSource.getWriter() != null) {
callback.streamResult(streamSource.getWriter());
return;
}
}
if (StringUtils.hasLength(result.getSystemId())) {
String systemId = result.getSystemId();
callback.result(systemId);
}
else {
throw new IllegalArgumentException("Unknown Result type: " + result.getClass());
}
}
/**
* Callback interface invoked on each sort of {@link Source}.
*
* @see TraxUtils#doWithSource(Source, SourceCallback)
*/
public interface SourceCallback {
/**
* Callback interface invoked on each sort of {@link Source}.
*
* @see TraxUtils#doWithSource(Source, SourceCallback)
*/
public interface SourceCallback {
/**
* Perform an operation on the node contained in a {@link DOMSource}.
*
* @param node the node
*/
void domSource(Node node) throws Exception;
/**
* Perform an operation on the node contained in a {@link DOMSource}.
*
* @param node the node
*/
void domSource(Node node) throws Exception;
/**
* Perform an operation on the {@code XMLReader} and {@code InputSource} contained in a {@link SAXSource}.
*
* @param reader the reader, can be {@code null}
* @param inputSource the input source, can be {@code null}
*/
void saxSource(XMLReader reader, InputSource inputSource) throws Exception;
/**
* Perform an operation on the {@code XMLReader} and {@code InputSource} contained in a {@link SAXSource}.
*
* @param reader the reader, can be {@code null}
* @param inputSource the input source, can be {@code null}
*/
void saxSource(XMLReader reader, InputSource inputSource) throws Exception;
/**
* Perform an operation on the {@code XMLEventReader} contained in a JAXP 1.4 {@link StAXSource} or Spring
* {@link StaxUtils#createStaxSource StaxSource}.
*
* @param eventReader the reader
*/
void staxSource(XMLEventReader eventReader) throws Exception;
/**
* Perform an operation on the {@code XMLEventReader} contained in a JAXP 1.4 {@link StAXSource} or Spring
* {@link StaxUtils#createStaxSource StaxSource}.
*
* @param eventReader the reader
*/
void staxSource(XMLEventReader eventReader) throws Exception;
/**
* Perform an operation on the {@code XMLStreamReader} contained in a JAXP 1.4 {@link StAXSource} or Spring
* {@link StaxUtils#createStaxSource StaxSource}.
*
* @param streamReader the reader
*/
void staxSource(XMLStreamReader streamReader) throws Exception;
/**
* Perform an operation on the {@code XMLStreamReader} contained in a JAXP 1.4 {@link StAXSource} or Spring
* {@link StaxUtils#createStaxSource StaxSource}.
*
* @param streamReader the reader
*/
void staxSource(XMLStreamReader streamReader) throws Exception;
/**
* Perform an operation on the {@code InputStream} contained in a {@link StreamSource}.
*
* @param inputStream the input stream
*/
void streamSource(InputStream inputStream) throws Exception;
/**
* Perform an operation on the {@code InputStream} contained in a {@link StreamSource}.
*
* @param inputStream the input stream
*/
void streamSource(InputStream inputStream) throws Exception;
/**
* Perform an operation on the {@code Reader} contained in a {@link StreamSource}.
*
* @param reader the reader
*/
void streamSource(Reader reader) throws Exception;
/**
* Perform an operation on the {@code Reader} contained in a {@link StreamSource}.
*
* @param reader the reader
*/
void streamSource(Reader reader) throws Exception;
/**
* Perform an operation on the system identifier contained in any {@link Source}.
*
* @param systemId the system identifier
*/
void source(String systemId) throws Exception;
/**
* Perform an operation on the system identifier contained in any {@link Source}.
*
* @param systemId the system identifier
*/
void source(String systemId) throws Exception;
}
}
/**
* Callback interface invoked on each sort of {@link Result}.
*
* @see TraxUtils#doWithResult(Result, ResultCallback)
*/
public interface ResultCallback {
/**
* Callback interface invoked on each sort of {@link Result}.
*
* @see TraxUtils#doWithResult(Result, ResultCallback)
*/
public interface ResultCallback {
/**
* Perform an operation on the node contained in a {@link DOMResult}.
*
* @param node the node
*/
void domResult(Node node) throws Exception;
/**
* Perform an operation on the node contained in a {@link DOMResult}.
*
* @param node the node
*/
void domResult(Node node) throws Exception;
/**
* Perform an operation on the {@code ContentHandler} and {@code LexicalHandler} contained in a {@link
* SAXResult}.
*
* @param contentHandler the content handler
* @param lexicalHandler the lexicalHandler, can be {@code null}
*/
void saxResult(ContentHandler contentHandler, LexicalHandler lexicalHandler) throws Exception;
/**
* Perform an operation on the {@code ContentHandler} and {@code LexicalHandler} contained in a {@link
* SAXResult}.
*
* @param contentHandler the content handler
* @param lexicalHandler the lexicalHandler, can be {@code null}
*/
void saxResult(ContentHandler contentHandler, LexicalHandler lexicalHandler) throws Exception;
/**
* Perform an operation on the {@code XMLEventWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring
* {@link StaxUtils#createStaxResult StaxResult}.
*
* @param eventWriter the writer
*/
void staxResult(XMLEventWriter eventWriter) throws Exception;
/**
* Perform an operation on the {@code XMLEventWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring
* {@link StaxUtils#createStaxResult StaxResult}.
*
* @param eventWriter the writer
*/
void staxResult(XMLEventWriter eventWriter) throws Exception;
/**
* Perform an operation on the {@code XMLStreamWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring
* {@link StaxUtils#createStaxResult StaxResult}.
*
* @param streamWriter the writer
*/
void staxResult(XMLStreamWriter streamWriter) throws Exception;
/**
* Perform an operation on the {@code XMLStreamWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring
* {@link StaxUtils#createStaxResult StaxResult}.
*
* @param streamWriter the writer
*/
void staxResult(XMLStreamWriter streamWriter) throws Exception;
/**
* Perform an operation on the {@code OutputStream} contained in a {@link StreamResult}.
*
* @param outputStream the output stream
*/
void streamResult(OutputStream outputStream) throws Exception;
/**
* Perform an operation on the {@code OutputStream} contained in a {@link StreamResult}.
*
* @param outputStream the output stream
*/
void streamResult(OutputStream outputStream) throws Exception;
/**
* Perform an operation on the {@code Writer} contained in a {@link StreamResult}.
*
* @param writer the writer
*/
void streamResult(Writer writer) throws Exception;
/**
* Perform an operation on the {@code Writer} contained in a {@link StreamResult}.
*
* @param writer the writer
*/
void streamResult(Writer writer) throws Exception;
/**
* Perform an operation on the system identifier contained in any {@link Result}.
*
* @param systemId the system identifier
*/
void result(String systemId) throws Exception;
/**
* Perform an operation on the system identifier contained in any {@link Result}.
*
* @param systemId the system identifier
*/
void result(String systemId) throws Exception;
}
}
}

View File

@@ -36,68 +36,68 @@ import org.springframework.core.io.Resource;
*/
abstract class Jaxp13ValidatorFactory {
static XmlValidator createValidator(Resource[] resources, String schemaLanguage) throws IOException {
try {
Schema schema = SchemaLoaderUtils.loadSchema(resources, schemaLanguage);
return new Jaxp13Validator(schema);
}
catch (SAXException ex) {
throw new XmlValidationException("Could not create Schema: " + ex.getMessage(), ex);
}
}
static XmlValidator createValidator(Resource[] resources, String schemaLanguage) throws IOException {
try {
Schema schema = SchemaLoaderUtils.loadSchema(resources, schemaLanguage);
return new Jaxp13Validator(schema);
}
catch (SAXException ex) {
throw new XmlValidationException("Could not create Schema: " + ex.getMessage(), ex);
}
}
private static class Jaxp13Validator implements XmlValidator {
private static class Jaxp13Validator implements XmlValidator {
private Schema schema;
private Schema schema;
public Jaxp13Validator(Schema schema) {
this.schema = schema;
}
public Jaxp13Validator(Schema schema) {
this.schema = schema;
}
@Override
public SAXParseException[] validate(Source source) throws IOException {
return validate(source, null);
}
@Override
public SAXParseException[] validate(Source source) throws IOException {
return validate(source, null);
}
@Override
public SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException {
if (errorHandler == null) {
errorHandler = new DefaultValidationErrorHandler();
}
Validator validator = schema.newValidator();
validator.setErrorHandler(errorHandler);
try {
validator.validate(source);
return errorHandler.getErrors();
}
catch (SAXException ex) {
throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex);
}
}
}
@Override
public SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException {
if (errorHandler == null) {
errorHandler = new DefaultValidationErrorHandler();
}
Validator validator = schema.newValidator();
validator.setErrorHandler(errorHandler);
try {
validator.validate(source);
return errorHandler.getErrors();
}
catch (SAXException ex) {
throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex);
}
}
}
/** {@code ErrorHandler} implementation that stores errors and fatal errors in a list. */
private static class DefaultValidationErrorHandler implements ValidationErrorHandler {
/** {@code ErrorHandler} implementation that stores errors and fatal errors in a list. */
private static class DefaultValidationErrorHandler implements ValidationErrorHandler {
private List<SAXParseException> errors = new ArrayList<SAXParseException>();
private List<SAXParseException> errors = new ArrayList<SAXParseException>();
@Override
public SAXParseException[] getErrors() {
return errors.toArray(new SAXParseException[errors.size()]);
}
@Override
public SAXParseException[] getErrors() {
return errors.toArray(new SAXParseException[errors.size()]);
}
@Override
public void warning(SAXParseException ex) throws SAXException {
}
@Override
public void warning(SAXParseException ex) throws SAXException {
}
@Override
public void error(SAXParseException ex) throws SAXException {
errors.add(ex);
}
@Override
public void error(SAXParseException ex) throws SAXException {
errors.add(ex);
}
@Override
public void fatalError(SAXParseException ex) throws SAXException {
errors.add(ex);
}
}
@Override
public void fatalError(SAXParseException ex) throws SAXException {
errors.add(ex);
}
}
}

View File

@@ -37,54 +37,54 @@ import org.xml.sax.helpers.XMLReaderFactory;
*/
public abstract class SchemaLoaderUtils {
/**
* Load schema from the given resource.
*
* @param resource the resource to load from
* @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or
* {@code XMLConstants.RELAXNG_NS_URI}.
* @throws IOException if loading failed
* @throws SAXException if loading failed
* @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI
* @see javax.xml.XMLConstants#RELAXNG_NS_URI
*/
public static Schema loadSchema(Resource resource, String schemaLanguage) throws IOException, SAXException {
return loadSchema(new Resource[]{resource}, schemaLanguage);
}
/**
* Load schema from the given resource.
*
* @param resource the resource to load from
* @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or
* {@code XMLConstants.RELAXNG_NS_URI}.
* @throws IOException if loading failed
* @throws SAXException if loading failed
* @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI
* @see javax.xml.XMLConstants#RELAXNG_NS_URI
*/
public static Schema loadSchema(Resource resource, String schemaLanguage) throws IOException, SAXException {
return loadSchema(new Resource[]{resource}, schemaLanguage);
}
/**
* Load schema from the given resource.
*
* @param resources the resources to load from
* @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or
* {@code XMLConstants.RELAXNG_NS_URI}.
* @throws IOException if loading failed
* @throws SAXException if loading failed
* @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI
* @see javax.xml.XMLConstants#RELAXNG_NS_URI
*/
public static Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
Assert.notEmpty(resources, "No resources given");
Assert.hasLength(schemaLanguage, "No schema language provided");
Source[] schemaSources = new Source[resources.length];
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
for (int i = 0; i < resources.length; i++) {
Assert.notNull(resources[i], "Resource is null");
Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
schemaSources[i] = new ResourceSource(xmlReader, resources[i]);
}
SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
return schemaFactory.newSchema(schemaSources);
}
/**
* Load schema from the given resource.
*
* @param resources the resources to load from
* @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or
* {@code XMLConstants.RELAXNG_NS_URI}.
* @throws IOException if loading failed
* @throws SAXException if loading failed
* @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI
* @see javax.xml.XMLConstants#RELAXNG_NS_URI
*/
public static Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
Assert.notEmpty(resources, "No resources given");
Assert.hasLength(schemaLanguage, "No schema language provided");
Source[] schemaSources = new Source[resources.length];
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
for (int i = 0; i < resources.length; i++) {
Assert.notNull(resources[i], "Resource is null");
Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
schemaSources[i] = new ResourceSource(xmlReader, resources[i]);
}
SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
return schemaFactory.newSchema(schemaSources);
}
/** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */
public static String getSystemId(Resource resource) {
try {
return resource.getURL().toString();
}
catch (IOException e) {
return null;
}
}
/** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */
public static String getSystemId(Resource resource) {
try {
return resource.getURL().toString();
}
catch (IOException e) {
return null;
}
}
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -26,9 +26,9 @@ import org.xml.sax.SAXParseException;
*/
public interface ValidationErrorHandler extends ErrorHandler {
/**
* Returns the errors collected by this error handler.
* @return the errors
*/
SAXParseException[] getErrors();
/**
* Returns the errors collected by this error handler.
* @return the errors
*/
SAXParseException[] getErrors();
}

View File

@@ -27,11 +27,11 @@ import org.springframework.xml.XmlException;
@SuppressWarnings("serial")
public class XmlValidationException extends XmlException {
public XmlValidationException(String s) {
super(s);
}
public XmlValidationException(String s) {
super(s);
}
public XmlValidationException(String s, Throwable throwable) {
super(s, throwable);
}
public XmlValidationException(String s, Throwable throwable) {
super(s, throwable);
}
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -32,27 +32,27 @@ import org.xml.sax.SAXParseException;
*/
public interface XmlValidator {
/**
* Validates the given {@link Source}, and returns an array of {@link SAXParseException}s as result. The array will
* be empty if no validation errors are found.
*
* @param source the input document
* @return an array of {@code SAXParseException}s
* @throws IOException if the {@code source} cannot be read
* @throws XmlValidationException if the {@code source} cannot be validated
*/
SAXParseException[] validate(Source source) throws IOException;
/**
* Validates the given {@link Source}, and returns an array of {@link SAXParseException}s as result. The array will
* be empty if no validation errors are found.
*
* @param source the input document
* @return an array of {@code SAXParseException}s
* @throws IOException if the {@code source} cannot be read
* @throws XmlValidationException if the {@code source} cannot be validated
*/
SAXParseException[] validate(Source source) throws IOException;
/**
* Validates the given {@link Source} and {@link ValidationErrorHandler}, and returns an array of {@link
* SAXParseException}s as result. The array will be empty if no validation errors are found.
*
* @param source the input document
* @param errorHandler the error handler to use. May be {@code null}, in which case a default will be used.
* @return an array of {@code SAXParseException}s
* @throws IOException if the {@code source} cannot be read
* @throws XmlValidationException if the {@code source} cannot be validated
*/
SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException;
/**
* Validates the given {@link Source} and {@link ValidationErrorHandler}, and returns an array of {@link
* SAXParseException}s as result. The array will be empty if no validation errors are found.
*
* @param source the input document
* @param errorHandler the error handler to use. May be {@code null}, in which case a default will be used.
* @return an array of {@code SAXParseException}s
* @throws IOException if the {@code source} cannot be read
* @throws XmlValidationException if the {@code source} cannot be validated
*/
SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException;
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -39,61 +39,61 @@ import org.apache.commons.logging.LogFactory;
*/
public abstract class XmlValidatorFactory {
private static final Log logger = LogFactory.getLog(XmlValidatorFactory.class);
private static final Log logger = LogFactory.getLog(XmlValidatorFactory.class);
/** Constant that defines a W3C XML Schema. */
public static final String SCHEMA_W3C_XML = "http://www.w3.org/2001/XMLSchema";
/** Constant that defines a W3C XML Schema. */
public static final String SCHEMA_W3C_XML = "http://www.w3.org/2001/XMLSchema";
/** Constant that defines a RELAX NG Schema. */
public static final String SCHEMA_RELAX_NG = "http://relaxng.org/ns/structure/1.0";
/** Constant that defines a RELAX NG Schema. */
public static final String SCHEMA_RELAX_NG = "http://relaxng.org/ns/structure/1.0";
/**
* Create a {@link XmlValidator} with the given schema resource and schema language type. The schema language must
* be one of the {@code SCHEMA_XXX} constants.
*
* @param schemaResource a resource that locates the schema to validate against
* @param schemaLanguage the language of the schema
* @return a validator
* @throws IOException if the schema resource cannot be read
* @throws IllegalArgumentException if the schema language is not supported
* @throws IllegalStateException if JAXP 1.0 cannot be located
* @throws XmlValidationException if a {@code XmlValidator} cannot be created
* @see #SCHEMA_RELAX_NG
* @see #SCHEMA_W3C_XML
*/
public static XmlValidator createValidator(Resource schemaResource, String schemaLanguage) throws IOException {
return createValidator(new Resource[]{schemaResource}, schemaLanguage);
}
/**
* Create a {@link XmlValidator} with the given schema resource and schema language type. The schema language must
* be one of the {@code SCHEMA_XXX} constants.
*
* @param schemaResource a resource that locates the schema to validate against
* @param schemaLanguage the language of the schema
* @return a validator
* @throws IOException if the schema resource cannot be read
* @throws IllegalArgumentException if the schema language is not supported
* @throws IllegalStateException if JAXP 1.0 cannot be located
* @throws XmlValidationException if a {@code XmlValidator} cannot be created
* @see #SCHEMA_RELAX_NG
* @see #SCHEMA_W3C_XML
*/
public static XmlValidator createValidator(Resource schemaResource, String schemaLanguage) throws IOException {
return createValidator(new Resource[]{schemaResource}, schemaLanguage);
}
/**
* Create a {@link XmlValidator} with the given schema resources and schema language type. The schema language must
* be one of the {@code SCHEMA_XXX} constants.
*
* @param schemaResources an array of resource that locate the schemas to validate against
* @param schemaLanguage the language of the schemas
* @return a validator
* @throws IOException if the schema resource cannot be read
* @throws IllegalArgumentException if the schema language is not supported
* @throws IllegalStateException if JAXP 1.0 cannot be located
* @throws XmlValidationException if a {@code XmlValidator} cannot be created
* @see #SCHEMA_RELAX_NG
* @see #SCHEMA_W3C_XML
*/
public static XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws IOException {
Assert.notEmpty(schemaResources, "No resources given");
Assert.hasLength(schemaLanguage, "No schema language provided");
Assert.isTrue(SCHEMA_W3C_XML.equals(schemaLanguage) || SCHEMA_RELAX_NG.equals(schemaLanguage),
"Invalid schema language: " + schemaLanguage);
for (Resource schemaResource : schemaResources) {
Assert.isTrue(schemaResource.exists(), "schema [" + schemaResource + "] does not exist");
}
if (JaxpVersion.getJaxpVersion() >= JaxpVersion.JAXP_13) {
logger.trace("Creating JAXP 1.3 XmlValidator");
return Jaxp13ValidatorFactory.createValidator(schemaResources, schemaLanguage);
}
else {
throw new IllegalStateException("Could not locate JAXP 1.3.");
}
}
/**
* Create a {@link XmlValidator} with the given schema resources and schema language type. The schema language must
* be one of the {@code SCHEMA_XXX} constants.
*
* @param schemaResources an array of resource that locate the schemas to validate against
* @param schemaLanguage the language of the schemas
* @return a validator
* @throws IOException if the schema resource cannot be read
* @throws IllegalArgumentException if the schema language is not supported
* @throws IllegalStateException if JAXP 1.0 cannot be located
* @throws XmlValidationException if a {@code XmlValidator} cannot be created
* @see #SCHEMA_RELAX_NG
* @see #SCHEMA_W3C_XML
*/
public static XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws IOException {
Assert.notEmpty(schemaResources, "No resources given");
Assert.hasLength(schemaLanguage, "No schema language provided");
Assert.isTrue(SCHEMA_W3C_XML.equals(schemaLanguage) || SCHEMA_RELAX_NG.equals(schemaLanguage),
"Invalid schema language: " + schemaLanguage);
for (Resource schemaResource : schemaResources) {
Assert.isTrue(schemaResource.exists(), "schema [" + schemaResource + "] does not exist");
}
if (JaxpVersion.getJaxpVersion() >= JaxpVersion.JAXP_13) {
logger.trace("Creating JAXP 1.3 XmlValidator");
return Jaxp13ValidatorFactory.createValidator(schemaResources, schemaLanguage);
}
else {
throw new IllegalStateException("Could not locate JAXP 1.3.");
}
}
}

View File

@@ -36,51 +36,51 @@ import org.springframework.xml.transform.TransformerObjectSupport;
*/
public abstract class AbstractXPathTemplate extends TransformerObjectSupport implements XPathOperations {
private Map<String, String> namespaces;
private Map<String, String> namespaces;
/** Returns namespaces used in the XPath expression. */
public Map<String, String> getNamespaces() {
return namespaces;
}
/** Returns namespaces used in the XPath expression. */
public Map<String, String> getNamespaces() {
return namespaces;
}
/** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
/** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
@Override
public final void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler)
throws XPathException {
evaluate(expression, context, new NodeCallbackHandlerNodeMapper(callbackHandler));
}
@Override
public final void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler)
throws XPathException {
evaluate(expression, context, new NodeCallbackHandlerNodeMapper(callbackHandler));
}
/** Static inner class that adapts a {@link NodeCallbackHandler} to the interface of {@link NodeMapper}. */
private static class NodeCallbackHandlerNodeMapper implements NodeMapper<Object> {
/** Static inner class that adapts a {@link NodeCallbackHandler} to the interface of {@link NodeMapper}. */
private static class NodeCallbackHandlerNodeMapper implements NodeMapper<Object> {
private final NodeCallbackHandler callbackHandler;
private final NodeCallbackHandler callbackHandler;
public NodeCallbackHandlerNodeMapper(NodeCallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
}
public NodeCallbackHandlerNodeMapper(NodeCallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
}
@Override
public Object mapNode(Node node, int nodeNum) throws DOMException {
callbackHandler.processNode(node);
return null;
}
}
@Override
public Object mapNode(Node node, int nodeNum) throws DOMException {
callbackHandler.processNode(node);
return null;
}
}
/**
* Returns the root element of the given source.
*
* @param source the source to get the root element from
* @return the root element
*/
protected Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
/**
* Returns the root element of the given source.
*
* @param source the source to get the root element from
* @return the root element
*/
protected Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
}

View File

@@ -36,144 +36,144 @@ import org.w3c.dom.Node;
*/
abstract class JaxenXPathExpressionFactory {
/**
* Creates a Jaxen {@code XPathExpression} from the given string expression.
*
* @param expression the XPath expression
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
static XPathExpression createXPathExpression(String expression) {
try {
XPath xpath = new DOMXPath(expression);
return new JaxenXpathExpression(xpath);
}
catch (JaxenException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
/**
* Creates a Jaxen {@code XPathExpression} from the given string expression.
*
* @param expression the XPath expression
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
static XPathExpression createXPathExpression(String expression) {
try {
XPath xpath = new DOMXPath(expression);
return new JaxenXpathExpression(xpath);
}
catch (JaxenException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
/**
* Creates a Jaxen {@code XPathExpression} from the given string expression and prefixes.
*
* @param expression the XPath expression
* @param namespaces the namespaces
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression, Map<String, String> namespaces) {
try {
XPath xpath = new DOMXPath(expression);
xpath.setNamespaceContext(new SimpleNamespaceContext(namespaces));
return new JaxenXpathExpression(xpath);
}
catch (JaxenException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
/**
* Creates a Jaxen {@code XPathExpression} from the given string expression and prefixes.
*
* @param expression the XPath expression
* @param namespaces the namespaces
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression, Map<String, String> namespaces) {
try {
XPath xpath = new DOMXPath(expression);
xpath.setNamespaceContext(new SimpleNamespaceContext(namespaces));
return new JaxenXpathExpression(xpath);
}
catch (JaxenException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
/** Jaxen implementation of the {@code XPathExpression} interface. */
private static class JaxenXpathExpression implements XPathExpression {
/** Jaxen implementation of the {@code XPathExpression} interface. */
private static class JaxenXpathExpression implements XPathExpression {
private XPath xpath;
private XPath xpath;
private JaxenXpathExpression(XPath xpath) {
this.xpath = xpath;
}
private JaxenXpathExpression(XPath xpath) {
this.xpath = xpath;
}
@Override
public Node evaluateAsNode(Node node) {
try {
return (Node) xpath.selectSingleNode(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public Node evaluateAsNode(Node node) {
try {
return (Node) xpath.selectSingleNode(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public boolean evaluateAsBoolean(Node node) {
try {
return xpath.booleanValueOf(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public boolean evaluateAsBoolean(Node node) {
try {
return xpath.booleanValueOf(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public double evaluateAsNumber(Node node) {
try {
return xpath.numberValueOf(node).doubleValue();
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public double evaluateAsNumber(Node node) {
try {
return xpath.numberValueOf(node).doubleValue();
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public String evaluateAsString(Node node) {
try {
return xpath.stringValueOf(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public String evaluateAsString(Node node) {
try {
return xpath.stringValueOf(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
@SuppressWarnings("unchecked")
public List<Node> evaluateAsNodeList(Node node) {
try {
return xpath.selectNodes(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
@SuppressWarnings("unchecked")
public List<Node> evaluateAsNodeList(Node node) {
try {
return xpath.selectNodes(node);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public <T> T evaluateAsObject(Node context, NodeMapper<T> nodeMapper) throws XPathException {
try {
Node result = (Node) xpath.selectSingleNode(context);
if (result != null) {
try {
return nodeMapper.mapNode(result, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public <T> T evaluateAsObject(Node context, NodeMapper<T> nodeMapper) throws XPathException {
try {
Node result = (Node) xpath.selectSingleNode(context);
if (result != null) {
try {
return nodeMapper.mapNode(result, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
@Override
public <T> List<T> evaluate(Node context, NodeMapper<T> nodeMapper) throws XPathException {
try {
List<?> nodes = xpath.selectNodes(context);
List<T> results = new ArrayList<T>(nodes.size());
for (int i = 0; i < nodes.size(); i++) {
Node node = (Node) nodes.get(i);
try {
results.add(nodeMapper.mapNode(node, i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
}
@Override
public <T> List<T> evaluate(Node context, NodeMapper<T> nodeMapper) throws XPathException {
try {
List<?> nodes = xpath.selectNodes(context);
List<T> results = new ArrayList<T>(nodes.size());
for (int i = 0; i < nodes.size(); i++) {
Node node = (Node) nodes.get(i);
try {
results.add(nodeMapper.mapNode(node, i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex);
}
}
}
}

View File

@@ -40,140 +40,140 @@ import org.w3c.dom.Node;
*/
public class JaxenXPathTemplate extends AbstractXPathTemplate {
@Override
public boolean evaluateAsBoolean(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.booleanValueOf(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public boolean evaluateAsBoolean(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.booleanValueOf(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public Node evaluateAsNode(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return (Node) xpath.selectSingleNode(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public Node evaluateAsNode(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return (Node) xpath.selectSingleNode(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
@SuppressWarnings("unchecked")
public List<Node> evaluateAsNodeList(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.selectNodes(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
@SuppressWarnings("unchecked")
public List<Node> evaluateAsNodeList(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.selectNodes(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public double evaluateAsDouble(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.numberValueOf(element).doubleValue();
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public double evaluateAsDouble(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.numberValueOf(element).doubleValue();
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public String evaluateAsString(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.stringValueOf(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public String evaluateAsString(String expression, Source context) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
return xpath.stringValueOf(element);
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public <T> T evaluateAsObject(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
Node node = (Node) xpath.selectSingleNode(element);
if (node != null) {
try {
return nodeMapper.mapNode(node, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
@Override
public <T> T evaluateAsObject(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
Node node = (Node) xpath.selectSingleNode(element);
if (node != null) {
try {
return nodeMapper.mapNode(node, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public <T> List<T> evaluate(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
List<?> nodes = xpath.selectNodes(element);
List<T> results = new ArrayList<T>(nodes.size());
for (int i = 0; i < nodes.size(); i++) {
Node node = (Node) nodes.get(i);
try {
results.add(nodeMapper.mapNode(node, i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
@Override
public <T> List<T> evaluate(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
try {
XPath xpath = createXPath(expression);
Element element = getRootElement(context);
List<?> nodes = xpath.selectNodes(element);
List<T> results = new ArrayList<T>(nodes.size());
for (int i = 0; i < nodes.size(); i++) {
Node node = (Node) nodes.get(i);
try {
results.add(nodeMapper.mapNode(node, i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
catch (JaxenException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
}
private XPath createXPath(String expression) throws JaxenException {
XPath xpath = new DOMXPath(expression);
if (getNamespaces() != null && !getNamespaces().isEmpty()) {
xpath.setNamespaceContext(new SimpleNamespaceContext(getNamespaces()));
}
return xpath;
}
private XPath createXPath(String expression) throws JaxenException {
XPath xpath = new DOMXPath(expression);
if (getNamespaces() != null && !getNamespaces().isEmpty()) {
xpath.setNamespaceContext(new SimpleNamespaceContext(getNamespaces()));
}
return xpath;
}
}

View File

@@ -40,140 +40,140 @@ import org.springframework.xml.namespace.SimpleNamespaceContext;
*/
abstract class Jaxp13XPathExpressionFactory {
private static XPathFactory xpathFactory = XPathFactory.newInstance();
private static XPathFactory xpathFactory = XPathFactory.newInstance();
/**
* Creates a JAXP 1.3 {@code XPathExpression} from the given string expression.
*
* @param expression the XPath expression
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
static XPathExpression createXPathExpression(String expression) {
try {
XPath xpath = createXPath();
javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression);
return new Jaxp13XPathExpression(xpathExpression);
}
catch (XPathExpressionException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
/**
* Creates a JAXP 1.3 {@code XPathExpression} from the given string expression.
*
* @param expression the XPath expression
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
static XPathExpression createXPathExpression(String expression) {
try {
XPath xpath = createXPath();
javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression);
return new Jaxp13XPathExpression(xpathExpression);
}
catch (XPathExpressionException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
/**
* Creates a JAXP 1.3 {@code XPathExpression} from the given string expression and namespaces.
*
* @param expression the XPath expression
* @param namespaces the namespaces
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression, Map<String, String> namespaces) {
try {
XPath xpath = createXPath();
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.setBindings(namespaces);
xpath.setNamespaceContext(namespaceContext);
javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression);
return new Jaxp13XPathExpression(xpathExpression);
}
catch (XPathExpressionException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
/**
* Creates a JAXP 1.3 {@code XPathExpression} from the given string expression and namespaces.
*
* @param expression the XPath expression
* @param namespaces the namespaces
* @return the compiled {@code XPathExpression}
* @throws XPathParseException when the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression, Map<String, String> namespaces) {
try {
XPath xpath = createXPath();
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.setBindings(namespaces);
xpath.setNamespaceContext(namespaceContext);
javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression);
return new Jaxp13XPathExpression(xpathExpression);
}
catch (XPathExpressionException ex) {
throw new org.springframework.xml.xpath.XPathParseException(
"Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex);
}
}
private static synchronized XPath createXPath() {
return xpathFactory.newXPath();
}
private static synchronized XPath createXPath() {
return xpathFactory.newXPath();
}
/** JAXP 1.3 implementation of the {@code XPathExpression} interface. */
private static class Jaxp13XPathExpression implements XPathExpression {
private final javax.xml.xpath.XPathExpression xpathExpression;
/** JAXP 1.3 implementation of the {@code XPathExpression} interface. */
private static class Jaxp13XPathExpression implements XPathExpression {
private Jaxp13XPathExpression(javax.xml.xpath.XPathExpression xpathExpression) {
this.xpathExpression = xpathExpression;
}
private final javax.xml.xpath.XPathExpression xpathExpression;
@Override
public String evaluateAsString(Node node) {
return (String) evaluate(node, XPathConstants.STRING);
}
private Jaxp13XPathExpression(javax.xml.xpath.XPathExpression xpathExpression) {
this.xpathExpression = xpathExpression;
}
@Override
public List<Node> evaluateAsNodeList(Node node) {
NodeList nodeList = (NodeList) evaluate(node, XPathConstants.NODESET);
return toNodeList(nodeList);
}
@Override
public String evaluateAsString(Node node) {
return (String) evaluate(node, XPathConstants.STRING);
}
private Object evaluate(Node node, QName returnType) {
try {
// XPathExpression is not thread-safe
synchronized (xpathExpression) {
return xpathExpression.evaluate(node, returnType);
}
}
catch (XPathExpressionException ex) {
throw new XPathException("Could not evaluate XPath expression:" + ex.getMessage(), ex);
}
}
@Override
public List<Node> evaluateAsNodeList(Node node) {
NodeList nodeList = (NodeList) evaluate(node, XPathConstants.NODESET);
return toNodeList(nodeList);
}
private List<Node> toNodeList(NodeList nodeList) {
List<Node> result = new ArrayList<Node>(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
result.add(nodeList.item(i));
}
return result;
}
private Object evaluate(Node node, QName returnType) {
try {
// XPathExpression is not thread-safe
synchronized (xpathExpression) {
return xpathExpression.evaluate(node, returnType);
}
}
catch (XPathExpressionException ex) {
throw new XPathException("Could not evaluate XPath expression:" + ex.getMessage(), ex);
}
}
@Override
public double evaluateAsNumber(Node node) {
return (Double) evaluate(node, XPathConstants.NUMBER);
}
private List<Node> toNodeList(NodeList nodeList) {
List<Node> result = new ArrayList<Node>(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
result.add(nodeList.item(i));
}
return result;
}
@Override
public boolean evaluateAsBoolean(Node node) {
return (Boolean) evaluate(node, XPathConstants.BOOLEAN);
}
@Override
public double evaluateAsNumber(Node node) {
return (Double) evaluate(node, XPathConstants.NUMBER);
}
@Override
public Node evaluateAsNode(Node node) {
return (Node) evaluate(node, XPathConstants.NODE);
}
@Override
public boolean evaluateAsBoolean(Node node) {
return (Boolean) evaluate(node, XPathConstants.BOOLEAN);
}
@Override
public <T> T evaluateAsObject(Node node, NodeMapper<T> nodeMapper) throws XPathException {
Node result = (Node) evaluate(node, XPathConstants.NODE);
if (result != null) {
try {
return nodeMapper.mapNode(result, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
}
@Override
public Node evaluateAsNode(Node node) {
return (Node) evaluate(node, XPathConstants.NODE);
}
@Override
public <T> List<T> evaluate(Node node, NodeMapper<T> nodeMapper) throws XPathException {
NodeList nodes = (NodeList) evaluate(node, XPathConstants.NODESET);
List<T> results = new ArrayList<T>(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
try {
results.add(nodeMapper.mapNode(nodes.item(i), i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
}
@Override
public <T> T evaluateAsObject(Node node, NodeMapper<T> nodeMapper) throws XPathException {
Node result = (Node) evaluate(node, XPathConstants.NODE);
if (result != null) {
try {
return nodeMapper.mapNode(result, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
}
@Override
public <T> List<T> evaluate(Node node, NodeMapper<T> nodeMapper) throws XPathException {
NodeList nodes = (NodeList) evaluate(node, XPathConstants.NODESET);
List<T> results = new ArrayList<T>(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
try {
results.add(nodeMapper.mapNode(nodes.item(i), i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
}
}

View File

@@ -57,179 +57,179 @@ import org.springframework.xml.transform.TraxUtils;
*/
public class Jaxp13XPathTemplate extends AbstractXPathTemplate {
private XPathFactory xpathFactory;
private XPathFactory xpathFactory;
public Jaxp13XPathTemplate() {
this(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
}
public Jaxp13XPathTemplate() {
this(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
}
public Jaxp13XPathTemplate(String xpathFactoryUri) {
try {
xpathFactory = XPathFactory.newInstance(xpathFactoryUri);
}
catch (XPathFactoryConfigurationException ex) {
throw new XPathException("Could not create XPathFactory", ex);
}
}
public Jaxp13XPathTemplate(String xpathFactoryUri) {
try {
xpathFactory = XPathFactory.newInstance(xpathFactoryUri);
}
catch (XPathFactoryConfigurationException ex) {
throw new XPathException("Could not create XPathFactory", ex);
}
}
@Override
public boolean evaluateAsBoolean(String expression, Source context) throws XPathException {
Boolean result = (Boolean) evaluate(expression, context, XPathConstants.BOOLEAN);
return result != null && result;
}
@Override
public boolean evaluateAsBoolean(String expression, Source context) throws XPathException {
Boolean result = (Boolean) evaluate(expression, context, XPathConstants.BOOLEAN);
return result != null && result;
}
@Override
public Node evaluateAsNode(String expression, Source context) throws XPathException {
return (Node) evaluate(expression, context, XPathConstants.NODE);
}
@Override
public Node evaluateAsNode(String expression, Source context) throws XPathException {
return (Node) evaluate(expression, context, XPathConstants.NODE);
}
@Override
public List<Node> evaluateAsNodeList(String expression, Source context) throws XPathException {
NodeList result = (NodeList) evaluate(expression, context, XPathConstants.NODESET);
List<Node> nodes = new ArrayList<Node>(result.getLength());
for (int i = 0; i < result.getLength(); i++) {
nodes.add(result.item(i));
}
return nodes;
}
@Override
public List<Node> evaluateAsNodeList(String expression, Source context) throws XPathException {
NodeList result = (NodeList) evaluate(expression, context, XPathConstants.NODESET);
List<Node> nodes = new ArrayList<Node>(result.getLength());
for (int i = 0; i < result.getLength(); i++) {
nodes.add(result.item(i));
}
return nodes;
}
@Override
public double evaluateAsDouble(String expression, Source context) throws XPathException {
Double result = (Double) evaluate(expression, context, XPathConstants.NUMBER);
return result != null ? result : Double.NaN;
}
@Override
public double evaluateAsDouble(String expression, Source context) throws XPathException {
Double result = (Double) evaluate(expression, context, XPathConstants.NUMBER);
return result != null ? result : Double.NaN;
}
@Override
public String evaluateAsString(String expression, Source context) throws XPathException {
return (String) evaluate(expression, context, XPathConstants.STRING);
}
@Override
public String evaluateAsString(String expression, Source context) throws XPathException {
return (String) evaluate(expression, context, XPathConstants.STRING);
}
@Override
public <T> T evaluateAsObject(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
Node node = evaluateAsNode(expression, context);
if (node != null) {
try {
return nodeMapper.mapNode(node, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
}
@Override
public <T> T evaluateAsObject(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
Node node = evaluateAsNode(expression, context);
if (node != null) {
try {
return nodeMapper.mapNode(node, 0);
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
else {
return null;
}
}
@Override
public <T> List<T> evaluate(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
NodeList nodes = (NodeList) evaluate(expression, context, XPathConstants.NODESET);
List<T> results = new ArrayList<T>(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
try {
results.add(nodeMapper.mapNode(nodes.item(i), i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
@Override
public <T> List<T> evaluate(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException {
NodeList nodes = (NodeList) evaluate(expression, context, XPathConstants.NODESET);
List<T> results = new ArrayList<T>(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
try {
results.add(nodeMapper.mapNode(nodes.item(i), i));
}
catch (DOMException ex) {
throw new XPathException("Mapping resulted in DOMException", ex);
}
}
return results;
}
private Object evaluate(String expression, Source context, QName returnType) throws XPathException {
XPath xpath = createXPath();
if (getNamespaces() != null && !getNamespaces().isEmpty()) {
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.setBindings(getNamespaces());
xpath.setNamespaceContext(namespaceContext);
}
try {
EvaluationCallback callback = new EvaluationCallback(xpath, expression, returnType);
TraxUtils.doWithSource(context, callback);
return callback.result;
}
catch (javax.xml.xpath.XPathException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
catch (Exception ex) {
throw new XPathException(ex.getMessage(), ex);
}
}
private Object evaluate(String expression, Source context, QName returnType) throws XPathException {
XPath xpath = createXPath();
if (getNamespaces() != null && !getNamespaces().isEmpty()) {
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.setBindings(getNamespaces());
xpath.setNamespaceContext(namespaceContext);
}
try {
EvaluationCallback callback = new EvaluationCallback(xpath, expression, returnType);
TraxUtils.doWithSource(context, callback);
return callback.result;
}
catch (javax.xml.xpath.XPathException ex) {
throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex);
}
catch (TransformerException ex) {
throw new XPathException("Could not transform context to DOM Node", ex);
}
catch (Exception ex) {
throw new XPathException(ex.getMessage(), ex);
}
}
private synchronized XPath createXPath() {
return xpathFactory.newXPath();
}
private synchronized XPath createXPath() {
return xpathFactory.newXPath();
}
private static class EvaluationCallback implements TraxUtils.SourceCallback {
private static class EvaluationCallback implements TraxUtils.SourceCallback {
private final XPath xpath;
private final XPath xpath;
private final String expression;
private final String expression;
private final QName returnType;
private final QName returnType;
private final TransformerHelper transformerHelper = new TransformerHelper();
private final TransformerHelper transformerHelper = new TransformerHelper();
private Object result;
private Object result;
private EvaluationCallback(XPath xpath, String expression, QName returnType) {
this.xpath = xpath;
this.expression = expression;
this.returnType = returnType;
}
private EvaluationCallback(XPath xpath, String expression, QName returnType) {
this.xpath = xpath;
this.expression = expression;
this.returnType = returnType;
}
@Override
public void domSource(Node node) throws XPathExpressionException {
result = xpath.evaluate(expression, node, returnType);
}
@Override
public void domSource(Node node) throws XPathExpressionException {
result = xpath.evaluate(expression, node, returnType);
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws XPathExpressionException {
inputSource(inputSource);
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws XPathExpressionException {
inputSource(inputSource);
}
@Override
public void staxSource(XMLEventReader eventReader)
throws XPathExpressionException, XMLStreamException, TransformerException {
Element element = getRootElement(StaxUtils.createCustomStaxSource(eventReader));
domSource(element);
}
@Override
public void staxSource(XMLEventReader eventReader)
throws XPathExpressionException, XMLStreamException, TransformerException {
Element element = getRootElement(StaxUtils.createCustomStaxSource(eventReader));
domSource(element);
}
@Override
public void staxSource(XMLStreamReader streamReader) throws TransformerException, XPathExpressionException {
Element element = getRootElement(StaxUtils.createCustomStaxSource(streamReader));
domSource(element);
}
@Override
public void staxSource(XMLStreamReader streamReader) throws TransformerException, XPathExpressionException {
Element element = getRootElement(StaxUtils.createCustomStaxSource(streamReader));
domSource(element);
}
@Override
public void streamSource(InputStream inputStream) throws XPathExpressionException {
inputSource(new InputSource(inputStream));
}
@Override
public void streamSource(InputStream inputStream) throws XPathExpressionException {
inputSource(new InputSource(inputStream));
}
@Override
public void streamSource(Reader reader) throws XPathExpressionException {
inputSource(new InputSource(reader));
}
@Override
public void streamSource(Reader reader) throws XPathExpressionException {
inputSource(new InputSource(reader));
}
@Override
public void source(String systemId) throws XPathExpressionException {
inputSource(new InputSource(systemId));
}
@Override
public void source(String systemId) throws XPathExpressionException {
inputSource(new InputSource(systemId));
}
private void inputSource(InputSource inputSource) throws XPathExpressionException {
result = xpath.evaluate(expression, inputSource, returnType);
}
private void inputSource(InputSource inputSource) throws XPathExpressionException {
result = xpath.evaluate(expression, inputSource, returnType);
}
private Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transformerHelper.transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
private Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transformerHelper.transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
}
}

View File

@@ -33,12 +33,12 @@ import org.w3c.dom.Node;
*/
public interface NodeCallbackHandler {
/**
* Processed a single node.
*
* @param node the node to map
* @throws DOMException in case of DOM errors
*/
void processNode(Node node) throws DOMException;
/**
* Processed a single node.
*
* @param node the node to map
* @throws DOMException in case of DOM errors
*/
void processNode(Node node) throws DOMException;
}

View File

@@ -33,14 +33,14 @@ import org.w3c.dom.Node;
*/
public interface NodeMapper<T> {
/**
* Maps a single node to an arbitrary object.
*
* @param node the node to map
* @param nodeNum the number of the current node
* @return object for the current node
* @throws DOMException in case of DOM errors
*/
T mapNode(Node node, int nodeNum) throws DOMException;
/**
* Maps a single node to an arbitrary object.
*
* @param node the node to map
* @param nodeNum the number of the current node
* @return object for the current node
* @throws DOMException in case of DOM errors
*/
T mapNode(Node node, int nodeNum) throws DOMException;
}

View File

@@ -27,22 +27,22 @@ import org.springframework.xml.XmlException;
@SuppressWarnings("serial")
public class XPathException extends XmlException {
/**
* Constructs a new instance of the {@code XPathException} with the specific detail message.
*
* @param message the detail message
*/
public XPathException(String message) {
super(message);
}
/**
* Constructs a new instance of the {@code XPathException} with the specific detail message.
*
* @param message the detail message
*/
public XPathException(String message) {
super(message);
}
/**
* Constructs a new instance of the {@code XPathException} with the specific detail message and exception.
*
* @param message the detail message
* @param throwable the wrapped exception
*/
public XPathException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructs a new instance of the {@code XPathException} with the specific detail message and exception.
*
* @param message the detail message
* @param throwable the wrapped exception
*/
public XPathException(String message, Throwable throwable) {
super(message, throwable);
}
}

View File

@@ -32,93 +32,93 @@ import org.w3c.dom.Node;
*/
public interface XPathExpression {
/**
* Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or
* {@code false} if it is invalid.
*
* <p>The return value is determined per the {@code boolean()} function defined in the XPath specification.
* This means that an expression that selects zero nodes will return {@code false}, while an expression that
* selects one or more nodes will return {@code true}.
* An expression that returns a string returns {@code false} for empty strings and {@code true} for all other
* strings.
* An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-boolean">XPath specification - boolean() function</a>
*/
boolean evaluateAsBoolean(Node node) throws XPathException;
/**
* Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or
* {@code false} if it is invalid.
*
* <p>The return value is determined per the {@code boolean()} function defined in the XPath specification.
* This means that an expression that selects zero nodes will return {@code false}, while an expression that
* selects one or more nodes will return {@code true}.
* An expression that returns a string returns {@code false} for empty strings and {@code true} for all other
* strings.
* An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-boolean">XPath specification - boolean() function</a>
*/
boolean evaluateAsBoolean(Node node) throws XPathException;
/**
* Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null}
* if it is invalid.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
Node evaluateAsNode(Node node) throws XPathException;
/**
* Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null}
* if it is invalid.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
Node evaluateAsNode(Node node) throws XPathException;
/**
* Evaluates the given expression, and returns all {@link Node} objects that conform to it. Returns an empty list if
* no result could be found.
*
* @param node the starting point
* @return a list of {@code Node}s that are selected by the expression
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
List<Node> evaluateAsNodeList(Node node) throws XPathException;
/**
* Evaluates the given expression, and returns all {@link Node} objects that conform to it. Returns an empty list if
* no result could be found.
*
* @param node the starting point
* @return a list of {@code Node}s that are selected by the expression
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
List<Node> evaluateAsNodeList(Node node) throws XPathException;
/**
* Evaluates the given expression as a number ({@code double}). Returns the numeric evaluation of the
* expression, or {@link Double#NaN} if it is invalid.
*
* <p>The return value is determined per the {@code number()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the number value of the first node.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-number">XPath specification - number() function</a>
*/
double evaluateAsNumber(Node node) throws XPathException;
/**
* Evaluates the given expression as a number ({@code double}). Returns the numeric evaluation of the
* expression, or {@link Double#NaN} if it is invalid.
*
* <p>The return value is determined per the {@code number()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the number value of the first node.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-number">XPath specification - number() function</a>
*/
double evaluateAsNumber(Node node) throws XPathException;
/**
* Evaluates the given expression as a String. Returns {@code null} if no result could be found.
*
* <p>The return value is determined per the {@code string()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the string value of the first node.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-string">XPath specification - string() function</a>
*/
String evaluateAsString(Node node) throws XPathException;
/**
* Evaluates the given expression as a String. Returns {@code null} if no result could be found.
*
* <p>The return value is determined per the {@code string()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the string value of the first node.
*
* @param node the starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-string">XPath specification - string() function</a>
*/
String evaluateAsString(Node node) throws XPathException;
/**
* Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}.
*
* @param node the starting point
* @param nodeMapper object that will map one object per node
* @return the single mapped object
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> T evaluateAsObject(Node node, NodeMapper<T> nodeMapper) throws XPathException;
/**
* Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}.
*
* @param node the starting point
* @param nodeMapper object that will map one object per node
* @return the single mapped object
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> T evaluateAsObject(Node node, NodeMapper<T> nodeMapper) throws XPathException;
/**
* Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link
* NodeMapper}.
*
* @param node the starting point
* @param nodeMapper object that will map one object per node
* @return the result list, containing mapped objects
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> List<T> evaluate(Node node, NodeMapper<T> nodeMapper) throws XPathException;
/**
* Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link
* NodeMapper}.
*
* @param node the starting point
* @param nodeMapper object that will map one object per node
* @return the result list, containing mapped objects
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> List<T> evaluate(Node node, NodeMapper<T> nodeMapper) throws XPathException;
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -37,45 +37,45 @@ import org.apache.commons.logging.LogFactory;
*/
public abstract class XPathExpressionFactory {
private static final Log logger = LogFactory.getLog(XPathExpressionFactory.class);
private static final Log logger = LogFactory.getLog(XPathExpressionFactory.class);
/**
* Create a compiled XPath expression using the given string.
*
* @param expression the XPath expression
* @return the compiled XPath expression
* @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available
* @throws XPathParseException if the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression)
throws IllegalStateException, XPathParseException {
return createXPathExpression(expression, Collections.<String, String>emptyMap());
}
/**
* Create a compiled XPath expression using the given string.
*
* @param expression the XPath expression
* @return the compiled XPath expression
* @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available
* @throws XPathParseException if the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression)
throws IllegalStateException, XPathParseException {
return createXPathExpression(expression, Collections.<String, String>emptyMap());
}
/**
* Create a compiled XPath expression using the given string and namespaces. The namespace map should consist of
* string prefixes mapped to string namespaces.
*
* @param expression the XPath expression
* @param namespaces a map that binds string prefixes to string namespaces
* @return the compiled XPath expression
* @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available
* @throws XPathParseException if the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression, Map<String, String> namespaces)
throws IllegalStateException, XPathParseException {
Assert.hasLength(expression, "expression is empty");
if (namespaces == null) {
namespaces = Collections.emptyMap();
}
try {
logger.trace("Creating [javax.xml.xpath.XPathExpression]");
return Jaxp13XPathExpressionFactory.createXPathExpression(expression, namespaces);
}
catch (XPathException e) {
throw e;
}
}
/**
* Create a compiled XPath expression using the given string and namespaces. The namespace map should consist of
* string prefixes mapped to string namespaces.
*
* @param expression the XPath expression
* @param namespaces a map that binds string prefixes to string namespaces
* @return the compiled XPath expression
* @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available
* @throws XPathParseException if the given expression cannot be parsed
*/
public static XPathExpression createXPathExpression(String expression, Map<String, String> namespaces)
throws IllegalStateException, XPathParseException {
Assert.hasLength(expression, "expression is empty");
if (namespaces == null) {
namespaces = Collections.emptyMap();
}
try {
logger.trace("Creating [javax.xml.xpath.XPathExpression]");
return Jaxp13XPathExpressionFactory.createXPathExpression(expression, namespaces);
}
catch (XPathException e) {
throw e;
}
}
}

View File

@@ -35,45 +35,45 @@ import org.springframework.util.CollectionUtils;
*/
public class XPathExpressionFactoryBean implements FactoryBean<XPathExpression>, InitializingBean {
private Map<String, String> namespaces;
private Map<String, String> namespaces;
private String expressionString;
private String expressionString;
private XPathExpression expression;
private XPathExpression expression;
/** Sets the XPath expression. Setting this property is required. */
public void setExpression(String expression) {
expressionString = expression;
}
/** Sets the XPath expression. Setting this property is required. */
public void setExpression(String expression) {
expressionString = expression;
}
/** Sets the namespaces for the expressions. The given properties binds string prefixes to string namespaces. */
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
/** Sets the namespaces for the expressions. The given properties binds string prefixes to string namespaces. */
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
@Override
public void afterPropertiesSet() throws IllegalStateException, XPathParseException {
Assert.notNull(expressionString, "expression is required");
if (CollectionUtils.isEmpty(namespaces)) {
expression = XPathExpressionFactory.createXPathExpression(expressionString);
}
else {
expression = XPathExpressionFactory.createXPathExpression(expressionString, namespaces);
}
}
@Override
public void afterPropertiesSet() throws IllegalStateException, XPathParseException {
Assert.notNull(expressionString, "expression is required");
if (CollectionUtils.isEmpty(namespaces)) {
expression = XPathExpressionFactory.createXPathExpression(expressionString);
}
else {
expression = XPathExpressionFactory.createXPathExpression(expressionString, namespaces);
}
}
@Override
public XPathExpression getObject() throws Exception {
return expression;
}
@Override
public XPathExpression getObject() throws Exception {
return expression;
}
@Override
public Class<? extends XPathExpression> getObjectType() {
return XPathExpression.class;
}
@Override
public Class<? extends XPathExpression> getObjectType() {
return XPathExpression.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public boolean isSingleton() {
return true;
}
}

View File

@@ -35,113 +35,113 @@ import org.w3c.dom.Node;
*/
public interface XPathOperations {
/**
* Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or
* {@code false} if it is invalid.
*
* <p>The return value is determined per the {@code boolean()} function defined in the XPath specification.
* This means that an expression that selects zero nodes will return {@code false}, while an expression that
* selects one or more nodes will return {@code true}.
* An expression that returns a string returns {@code false} for empty strings and {@code true} for all other
* strings.
* An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-boolean">XPath specification - boolean() function</a>
*/
boolean evaluateAsBoolean(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or
* {@code false} if it is invalid.
*
* <p>The return value is determined per the {@code boolean()} function defined in the XPath specification.
* This means that an expression that selects zero nodes will return {@code false}, while an expression that
* selects one or more nodes will return {@code true}.
* An expression that returns a string returns {@code false} for empty strings and {@code true} for all other
* strings.
* An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-boolean">XPath specification - boolean() function</a>
*/
boolean evaluateAsBoolean(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null}
* if it is invalid.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
Node evaluateAsNode(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null}
* if it is invalid.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
Node evaluateAsNode(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a list of {@link Node} objects. Returns the evaluation of the expression, or an
* empty list if no results are found.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
List<Node> evaluateAsNodeList(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a list of {@link Node} objects. Returns the evaluation of the expression, or an
* empty list if no results are found.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
List<Node> evaluateAsNodeList(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a {@code double}. Returns the evaluation of the expression, or {@link
* Double#NaN} if it is invalid.
*
* <p>The return value is determined per the {@code number()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the number value of the first node.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-number">XPath specification - number() function</a>
*/
double evaluateAsDouble(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a {@code double}. Returns the evaluation of the expression, or {@link
* Double#NaN} if it is invalid.
*
* <p>The return value is determined per the {@code number()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the number value of the first node.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-number">XPath specification - number() function</a>
*/
double evaluateAsDouble(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a {@link String}. Returns the evaluation of the expression, or
* {@code null} if it is invalid.
*
* <p>The return value is determined per the {@code string()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the string value of the first node.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-string">XPath specification - string() function</a>
*/
String evaluateAsString(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression as a {@link String}. Returns the evaluation of the expression, or
* {@code null} if it is invalid.
*
* <p>The return value is determined per the {@code string()} function as defined in the XPath specification.
* This means that if the expression selects multiple nodes, it will return the string value of the first node.
*
* @param expression the XPath expression
* @param context the context starting point
* @return the result of the evaluation
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath/#function-string">XPath specification - string() function</a>
*/
String evaluateAsString(String expression, Source context) throws XPathException;
/**
* Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}.
*
* @param expression the XPath expression
* @param context the context starting point
* @param nodeMapper object that will map one object per node
* @return the single mapped object
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> T evaluateAsObject(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException;
/**
* Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}.
*
* @param expression the XPath expression
* @param context the context starting point
* @param nodeMapper object that will map one object per node
* @return the single mapped object
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> T evaluateAsObject(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException;
/**
* Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link
* NodeMapper}.
*
* @param expression the XPath expression
* @param context the context starting point
* @param nodeMapper object that will map one object per node
* @return the result list, containing mapped objects
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> List<T> evaluate(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException;
/**
* Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link
* NodeMapper}.
*
* @param expression the XPath expression
* @param context the context starting point
* @param nodeMapper object that will map one object per node
* @return the result list, containing mapped objects
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
<T> List<T> evaluate(String expression, Source context, NodeMapper<T> nodeMapper) throws XPathException;
/**
* Evaluates the given expression, handling the result {@link Node} objects on a per-node basis with a {@link
* NodeCallbackHandler}.
*
* @param expression the XPath expression
* @param context the context starting point
* @param callbackHandler object that will extract results, one row at a time
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler) throws XPathException;
/**
* Evaluates the given expression, handling the result {@link Node} objects on a per-node basis with a {@link
* NodeCallbackHandler}.
*
* @param expression the XPath expression
* @param context the context starting point
* @param callbackHandler object that will extract results, one row at a time
* @throws XPathException in case of XPath errors
* @see <a href="http://www.w3.org/TR/xpath#node-sets">XPath specification</a>
*/
void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler) throws XPathException;
}

View File

@@ -25,23 +25,23 @@ package org.springframework.xml.xpath;
@SuppressWarnings("serial")
public class XPathParseException extends XPathException {
/**
* Constructs a new instance of the {@code XPathParseException} with the specific detail message.
*
* @param message the detail message
*/
public XPathParseException(String message) {
super(message);
}
/**
* Constructs a new instance of the {@code XPathParseException} with the specific detail message.
*
* @param message the detail message
*/
public XPathParseException(String message) {
super(message);
}
/**
* Constructs a new instance of the {@code XPathParseException} with the specific detail message and
* exception.
*
* @param message the detail message
* @param throwable the wrapped exception
*/
public XPathParseException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* Constructs a new instance of the {@code XPathParseException} with the specific detail message and
* exception.
*
* @param message the detail message
* @param throwable the wrapped exception
*/
public XPathParseException(String message, Throwable throwable) {
super(message, throwable);
}
}

View File

@@ -47,93 +47,93 @@ import org.springframework.xml.validation.XmlValidatorFactory;
*/
public class SimpleXsdSchema implements XsdSchema, InitializingBean {
private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private static final String SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema";
private static final String SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema";
private static final QName SCHEMA_NAME = new QName(SCHEMA_NAMESPACE, "schema", "xsd");
private static final QName SCHEMA_NAME = new QName(SCHEMA_NAMESPACE, "schema", "xsd");
private Resource xsdResource;
private Element schemaElement;
private Element schemaElement;
static {
documentBuilderFactory.setNamespaceAware(true);
}
static {
documentBuilderFactory.setNamespaceAware(true);
}
/**
* Create a new instance of the {@link SimpleXsdSchema} class.
*
* <p>A subsequent call to the {@link #setXsd(Resource)} method is required.
*/
public SimpleXsdSchema() {
}
/**
* Create a new instance of the {@link SimpleXsdSchema} class.
*
* <p>A subsequent call to the {@link #setXsd(Resource)} method is required.
*/
public SimpleXsdSchema() {
}
/**
* Create a new instance of the {@link SimpleXsdSchema} class with the specified resource.
*
* @param xsdResource the XSD resource; must not be {@code null}
* @throws IllegalArgumentException if the supplied {@code xsdResource} is {@code null}
*/
public SimpleXsdSchema(Resource xsdResource) {
Assert.notNull(xsdResource, "xsdResource must not be null");
this.xsdResource = xsdResource;
}
/**
* Create a new instance of the {@link SimpleXsdSchema} class with the specified resource.
*
* @param xsdResource the XSD resource; must not be {@code null}
* @throws IllegalArgumentException if the supplied {@code xsdResource} is {@code null}
*/
public SimpleXsdSchema(Resource xsdResource) {
Assert.notNull(xsdResource, "xsdResource must not be null");
this.xsdResource = xsdResource;
}
/**
* Set the XSD resource to be exposed by calls to this instances' {@link #getSource()} method.
*
* @param xsdResource the XSD resource
*/
public void setXsd(Resource xsdResource) {
this.xsdResource = xsdResource;
}
/**
* Set the XSD resource to be exposed by calls to this instances' {@link #getSource()} method.
*
* @param xsdResource the XSD resource
*/
public void setXsd(Resource xsdResource) {
this.xsdResource = xsdResource;
}
@Override
public String getTargetNamespace() {
return schemaElement.getAttribute("targetNamespace");
}
@Override
public String getTargetNamespace() {
return schemaElement.getAttribute("targetNamespace");
}
@Override
public Source getSource() {
return new DOMSource(schemaElement);
}
@Override
public Source getSource() {
return new DOMSource(schemaElement);
}
@Override
public XmlValidator createValidator() {
try {
return XmlValidatorFactory.createValidator(xsdResource, XmlValidatorFactory.SCHEMA_W3C_XML);
}
catch (IOException ex) {
throw new XsdSchemaException(ex.getMessage(), ex);
}
}
@Override
public XmlValidator createValidator() {
try {
return XmlValidatorFactory.createValidator(xsdResource, XmlValidatorFactory.SCHEMA_W3C_XML);
}
catch (IOException ex) {
throw new XsdSchemaException(ex.getMessage(), ex);
}
}
@Override
public void afterPropertiesSet() throws ParserConfigurationException, IOException, SAXException {
Assert.notNull(xsdResource, "'xsd' is required");
Assert.isTrue(this.xsdResource.exists(), "xsd '" + this.xsdResource + "' does not exist");
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
loadSchema(documentBuilder);
}
@Override
public void afterPropertiesSet() throws ParserConfigurationException, IOException, SAXException {
Assert.notNull(xsdResource, "'xsd' is required");
Assert.isTrue(this.xsdResource.exists(), "xsd '" + this.xsdResource + "' does not exist");
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
loadSchema(documentBuilder);
}
private void loadSchema(DocumentBuilder documentBuilder) throws SAXException, IOException {
Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(xsdResource));
schemaElement = schemaDocument.getDocumentElement();
Assert.isTrue(SCHEMA_NAME.getLocalPart().equals(schemaElement.getLocalName()),
xsdResource + " has invalid root element : [" + schemaElement.getLocalName() + "] instead of [schema]");
Assert.isTrue(SCHEMA_NAME.getNamespaceURI().equals(schemaElement.getNamespaceURI()), xsdResource +
" has invalid root element: [" + schemaElement.getNamespaceURI() + "] instead of [" +
SCHEMA_NAME.getNamespaceURI() + "]");
Assert.hasText(getTargetNamespace(), xsdResource + " has no targetNamespace");
}
private void loadSchema(DocumentBuilder documentBuilder) throws SAXException, IOException {
Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(xsdResource));
schemaElement = schemaDocument.getDocumentElement();
Assert.isTrue(SCHEMA_NAME.getLocalPart().equals(schemaElement.getLocalName()),
xsdResource + " has invalid root element : [" + schemaElement.getLocalName() + "] instead of [schema]");
Assert.isTrue(SCHEMA_NAME.getNamespaceURI().equals(schemaElement.getNamespaceURI()), xsdResource +
" has invalid root element: [" + schemaElement.getNamespaceURI() + "] instead of [" +
SCHEMA_NAME.getNamespaceURI() + "]");
Assert.hasText(getTargetNamespace(), xsdResource + " has no targetNamespace");
}
public String toString() {
StringBuilder builder = new StringBuilder("SimpleXsdSchema");
builder.append('{');
builder.append(getTargetNamespace());
builder.append('}');
return builder.toString();
}
public String toString() {
StringBuilder builder = new StringBuilder("SimpleXsdSchema");
builder.append('{');
builder.append(getTargetNamespace());
builder.append('}');
return builder.toString();
}
}

View File

@@ -29,24 +29,24 @@ import org.springframework.xml.validation.XmlValidator;
*/
public interface XsdSchema {
/**
* Returns the target namespace of this schema.
*
* @return the target namespace
*/
String getTargetNamespace();
/**
* Returns the target namespace of this schema.
*
* @return the target namespace
*/
String getTargetNamespace();
/**
* Returns the {@link Source} of the schema.
*
* @return the source of this XSD schema
*/
Source getSource();
/**
* Returns the {@link Source} of the schema.
*
* @return the source of this XSD schema
*/
Source getSource();
/**
* Creates a {@link XmlValidator} based on the schema.
*
* @return a validator for this schema
*/
XmlValidator createValidator();
/**
* Creates a {@link XmlValidator} based on the schema.
*
* @return a validator for this schema
*/
XmlValidator createValidator();
}

View File

@@ -26,18 +26,18 @@ import org.springframework.xml.validation.XmlValidator;
*/
public interface XsdSchemaCollection {
/**
* Returns all schemas contained in this collection.
*
* @return the schemas contained in this collection
*/
XsdSchema[] getXsdSchemas();
/**
* Returns all schemas contained in this collection.
*
* @return the schemas contained in this collection
*/
XsdSchema[] getXsdSchemas();
/**
* Creates a {@link XmlValidator} based on the schemas contained in this collection.
*
* @return a validator for this collection
*/
XmlValidator createValidator();
/**
* Creates a {@link XmlValidator} based on the schemas contained in this collection.
*
* @return a validator for this collection
*/
XmlValidator createValidator();
}

View File

@@ -28,11 +28,11 @@ import org.springframework.xml.XmlException;
@SuppressWarnings("serial")
public class XsdSchemaException extends XmlException {
public XsdSchemaException(String message) {
super(message);
}
public XsdSchemaException(String message) {
super(message);
}
public XsdSchemaException(String message, Throwable throwable) {
super(message, throwable);
}
public XsdSchemaException(String message, Throwable throwable) {
super(message, throwable);
}
}

View File

@@ -50,95 +50,95 @@ import org.springframework.xml.xsd.XsdSchema;
*/
public class CommonsXsdSchema implements XsdSchema {
private final XmlSchema schema;
private final XmlSchema schema;
private final XmlSchemaCollection collection;
private final XmlSchemaCollection collection;
/**
* Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} reference.
*
* @param schema the Commons {@code XmlSchema} object; must not be {@code null}
* @throws IllegalArgumentException if the supplied {@code schema} is {@code null}
*/
protected CommonsXsdSchema(XmlSchema schema) {
this(schema, null);
}
/**
* Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} reference.
*
* @param schema the Commons {@code XmlSchema} object; must not be {@code null}
* @throws IllegalArgumentException if the supplied {@code schema} is {@code null}
*/
protected CommonsXsdSchema(XmlSchema schema) {
this(schema, null);
}
/**
* Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} and {@link
* XmlSchemaCollection} reference.
*
* @param schema the Commons {@code XmlSchema} object; must not be {@code null}
* @param collection the Commons {@code XmlSchemaCollection} object; can be {@code null}
* @throws IllegalArgumentException if the supplied {@code schema} is {@code null}
*/
protected CommonsXsdSchema(XmlSchema schema, XmlSchemaCollection collection) {
Assert.notNull(schema, "'schema' must not be null");
this.schema = schema;
this.collection = collection;
}
/**
* Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} and {@link
* XmlSchemaCollection} reference.
*
* @param schema the Commons {@code XmlSchema} object; must not be {@code null}
* @param collection the Commons {@code XmlSchemaCollection} object; can be {@code null}
* @throws IllegalArgumentException if the supplied {@code schema} is {@code null}
*/
protected CommonsXsdSchema(XmlSchema schema, XmlSchemaCollection collection) {
Assert.notNull(schema, "'schema' must not be null");
this.schema = schema;
this.collection = collection;
}
@Override
public String getTargetNamespace() {
return schema.getTargetNamespace();
}
@Override
public String getTargetNamespace() {
return schema.getTargetNamespace();
}
public QName[] getElementNames() {
List<QName> result = new ArrayList<QName>(schema.getElements().keySet());
return result.toArray(new QName[result.size()]);
}
public QName[] getElementNames() {
List<QName> result = new ArrayList<QName>(schema.getElements().keySet());
return result.toArray(new QName[result.size()]);
}
@Override
public Source getSource() {
// try to use the the package-friendly XmlSchemaSerializer first, fall back to slower stream-based version
try {
XmlSchemaSerializer serializer = BeanUtils.instantiateClass(XmlSchemaSerializer.class);
if (collection != null) {
serializer.setExtReg(collection.getExtReg());
}
Document[] serializedSchemas = serializer.serializeSchema(schema, false);
return new DOMSource(serializedSchemas[0]);
}
catch (BeanInstantiationException ex) {
// ignore
}
catch (XmlSchemaSerializer.XmlSchemaSerializerException ex) {
// ignore
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
schema.write(bos);
}
catch (UnsupportedEncodingException ex) {
throw new CommonsXsdSchemaException(ex.getMessage(), ex);
}
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
return new StreamSource(bis);
}
@Override
public Source getSource() {
// try to use the the package-friendly XmlSchemaSerializer first, fall back to slower stream-based version
try {
XmlSchemaSerializer serializer = BeanUtils.instantiateClass(XmlSchemaSerializer.class);
if (collection != null) {
serializer.setExtReg(collection.getExtReg());
}
Document[] serializedSchemas = serializer.serializeSchema(schema, false);
return new DOMSource(serializedSchemas[0]);
}
catch (BeanInstantiationException ex) {
// ignore
}
catch (XmlSchemaSerializer.XmlSchemaSerializerException ex) {
// ignore
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
schema.write(bos);
}
catch (UnsupportedEncodingException ex) {
throw new CommonsXsdSchemaException(ex.getMessage(), ex);
}
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
return new StreamSource(bis);
}
@Override
public XmlValidator createValidator() {
try {
Resource resource = new UrlResource(schema.getSourceURI());
return XmlValidatorFactory
.createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML);
}
catch (IOException ex) {
throw new CommonsXsdSchemaException(ex.getMessage(), ex);
}
}
@Override
public XmlValidator createValidator() {
try {
Resource resource = new UrlResource(schema.getSourceURI());
return XmlValidatorFactory
.createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML);
}
catch (IOException ex) {
throw new CommonsXsdSchemaException(ex.getMessage(), ex);
}
}
/** Returns the wrapped Commons {@code XmlSchema} object. */
public XmlSchema getSchema() {
return schema;
}
/** Returns the wrapped Commons {@code XmlSchema} object. */
public XmlSchema getSchema() {
return schema;
}
public String toString() {
StringBuilder builder = new StringBuilder("CommonsXsdSchema");
builder.append('{');
builder.append(getTargetNamespace());
builder.append('}');
return builder.toString();
}
public String toString() {
StringBuilder builder = new StringBuilder("CommonsXsdSchema");
builder.append('{');
builder.append(getTargetNamespace());
builder.append('}');
return builder.toString();
}
}

View File

@@ -60,225 +60,225 @@ import org.springframework.xml.xsd.XsdSchemaCollection;
*/
public class CommonsXsdSchemaCollection implements XsdSchemaCollection, InitializingBean, ResourceLoaderAware {
private static final Log logger = LogFactory.getLog(CommonsXsdSchemaCollection.class);
private static final Log logger = LogFactory.getLog(CommonsXsdSchemaCollection.class);
private final XmlSchemaCollection schemaCollection = new XmlSchemaCollection();
private final XmlSchemaCollection schemaCollection = new XmlSchemaCollection();
private final List<XmlSchema> xmlSchemas = new ArrayList<XmlSchema>();
private final List<XmlSchema> xmlSchemas = new ArrayList<XmlSchema>();
private Resource[] xsdResources;
private Resource[] xsdResources;
private boolean inline = false;
private boolean inline = false;
private URIResolver uriResolver = new ClasspathUriResolver();
private URIResolver uriResolver = new ClasspathUriResolver();
private ResourceLoader resourceLoader;
private ResourceLoader resourceLoader;
/**
* Constructs a new, empty instance of the {@code CommonsXsdSchemaCollection}.
*
* <p>A subsequent call to the {@link #setXsds(Resource[])} is required.
*/
public CommonsXsdSchemaCollection() {
}
/**
* Constructs a new, empty instance of the {@code CommonsXsdSchemaCollection}.
*
* <p>A subsequent call to the {@link #setXsds(Resource[])} is required.
*/
public CommonsXsdSchemaCollection() {
}
/**
* Constructs a new instance of the {@code CommonsXsdSchemaCollection} based on the given resources.
*
* @param resources the schema resources to load
*/
public CommonsXsdSchemaCollection(Resource[] resources) {
this.xsdResources = resources;
}
/**
* Constructs a new instance of the {@code CommonsXsdSchemaCollection} based on the given resources.
*
* @param resources the schema resources to load
*/
public CommonsXsdSchemaCollection(Resource[] resources) {
this.xsdResources = resources;
}
/**
* Sets the schema resources to be loaded.
*
* @param xsdResources the schema resources to be loaded
*/
public void setXsds(Resource[] xsdResources) {
this.xsdResources = xsdResources;
}
/**
* Sets the schema resources to be loaded.
*
* @param xsdResources the schema resources to be loaded
*/
public void setXsds(Resource[] xsdResources) {
this.xsdResources = xsdResources;
}
/**
* Defines whether included schemas should be inlined into the including schema.
*
* <p>Defaults to {@code false}.
*/
public void setInline(boolean inline) {
this.inline = inline;
}
/**
* Defines whether included schemas should be inlined into the including schema.
*
* <p>Defaults to {@code false}.
*/
public void setInline(boolean inline) {
this.inline = inline;
}
/**
* Sets the WS-Commons uri resolver to use when resolving (relative) schemas.
*
* <p>Default is an internal subclass of {@link DefaultURIResolver} which correctly handles schemas on the classpath.
*/
public void setUriResolver(URIResolver uriResolver) {
Assert.notNull(uriResolver, "'uriResolver' must not be null");
this.uriResolver = uriResolver;
}
/**
* Sets the WS-Commons uri resolver to use when resolving (relative) schemas.
*
* <p>Default is an internal subclass of {@link DefaultURIResolver} which correctly handles schemas on the classpath.
*/
public void setUriResolver(URIResolver uriResolver) {
Assert.notNull(uriResolver, "'uriResolver' must not be null");
this.uriResolver = uriResolver;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void afterPropertiesSet() throws IOException {
Assert.notEmpty(xsdResources, "'xsds' must not be empty");
@Override
public void afterPropertiesSet() throws IOException {
Assert.notEmpty(xsdResources, "'xsds' must not be empty");
schemaCollection.setSchemaResolver(uriResolver);
schemaCollection.setSchemaResolver(uriResolver);
Set<XmlSchema> processedIncludes = new HashSet<XmlSchema>();
Set<XmlSchema> processedImports = new HashSet<XmlSchema>();
Set<XmlSchema> processedIncludes = new HashSet<XmlSchema>();
Set<XmlSchema> processedImports = new HashSet<XmlSchema>();
for (Resource xsdResource : xsdResources) {
Assert.isTrue(xsdResource.exists(), xsdResource + " does not exit");
try {
XmlSchema xmlSchema =
schemaCollection.read(SaxUtils.createInputSource(xsdResource));
xmlSchemas.add(xmlSchema);
for (Resource xsdResource : xsdResources) {
Assert.isTrue(xsdResource.exists(), xsdResource + " does not exit");
try {
XmlSchema xmlSchema =
schemaCollection.read(SaxUtils.createInputSource(xsdResource));
xmlSchemas.add(xmlSchema);
if (inline) {
inlineIncludes(xmlSchema, processedIncludes, processedImports);
findImports(xmlSchema, processedImports, processedIncludes);
}
}
catch (Exception ex) {
throw new CommonsXsdSchemaException("Schema [" + xsdResource + "] could not be loaded", ex);
}
}
if (logger.isInfoEnabled()) {
logger.info("Loaded " + StringUtils.arrayToCommaDelimitedString(xsdResources));
}
if (inline) {
inlineIncludes(xmlSchema, processedIncludes, processedImports);
findImports(xmlSchema, processedImports, processedIncludes);
}
}
catch (Exception ex) {
throw new CommonsXsdSchemaException("Schema [" + xsdResource + "] could not be loaded", ex);
}
}
if (logger.isInfoEnabled()) {
logger.info("Loaded " + StringUtils.arrayToCommaDelimitedString(xsdResources));
}
}
}
@Override
public XsdSchema[] getXsdSchemas() {
XsdSchema[] result = new XsdSchema[xmlSchemas.size()];
for (int i = 0; i < xmlSchemas.size(); i++) {
XmlSchema xmlSchema = xmlSchemas.get(i);
result[i] = new CommonsXsdSchema(xmlSchema, schemaCollection);
}
return result;
}
@Override
public XsdSchema[] getXsdSchemas() {
XsdSchema[] result = new XsdSchema[xmlSchemas.size()];
for (int i = 0; i < xmlSchemas.size(); i++) {
XmlSchema xmlSchema = xmlSchemas.get(i);
result[i] = new CommonsXsdSchema(xmlSchema, schemaCollection);
}
return result;
}
@Override
public XmlValidator createValidator() {
try {
Resource[] resources = new Resource[xmlSchemas.size()];
for (int i = xmlSchemas.size() - 1; i >= 0; i--) {
XmlSchema xmlSchema = xmlSchemas.get(i);
String sourceUri = xmlSchema.getSourceURI();
if (StringUtils.hasLength(sourceUri)) {
resources[i] = new UrlResource(sourceUri);
}
}
return XmlValidatorFactory
.createValidator(resources, XmlValidatorFactory.SCHEMA_W3C_XML);
} catch (IOException ex) {
throw new CommonsXsdSchemaException(ex.getMessage(), ex);
}
}
@Override
public XmlValidator createValidator() {
try {
Resource[] resources = new Resource[xmlSchemas.size()];
for (int i = xmlSchemas.size() - 1; i >= 0; i--) {
XmlSchema xmlSchema = xmlSchemas.get(i);
String sourceUri = xmlSchema.getSourceURI();
if (StringUtils.hasLength(sourceUri)) {
resources[i] = new UrlResource(sourceUri);
}
}
return XmlValidatorFactory
.createValidator(resources, XmlValidatorFactory.SCHEMA_W3C_XML);
} catch (IOException ex) {
throw new CommonsXsdSchemaException(ex.getMessage(), ex);
}
}
private void inlineIncludes(XmlSchema schema, Set<XmlSchema> processedIncludes, Set<XmlSchema> processedImports) {
processedIncludes.add(schema);
private void inlineIncludes(XmlSchema schema, Set<XmlSchema> processedIncludes, Set<XmlSchema> processedImports) {
processedIncludes.add(schema);
List<XmlSchemaObject> schemaItems = schema.getItems();
for (int i = 0; i < schemaItems.size(); i++) {
XmlSchemaObject schemaObject = schemaItems.get(i);
if (schemaObject instanceof XmlSchemaInclude) {
XmlSchema includedSchema = ((XmlSchemaInclude) schemaObject).getSchema();
if (!processedIncludes.contains(includedSchema)) {
inlineIncludes(includedSchema, processedIncludes, processedImports);
findImports(includedSchema, processedImports, processedIncludes);
List<XmlSchemaObject> includeItems = includedSchema.getItems();
for (XmlSchemaObject includedItem : includeItems) {
schemaItems.add(includedItem);
}
}
// remove the <include/>
schemaItems.remove(i);
i--;
}
}
}
List<XmlSchemaObject> schemaItems = schema.getItems();
for (int i = 0; i < schemaItems.size(); i++) {
XmlSchemaObject schemaObject = schemaItems.get(i);
if (schemaObject instanceof XmlSchemaInclude) {
XmlSchema includedSchema = ((XmlSchemaInclude) schemaObject).getSchema();
if (!processedIncludes.contains(includedSchema)) {
inlineIncludes(includedSchema, processedIncludes, processedImports);
findImports(includedSchema, processedImports, processedIncludes);
List<XmlSchemaObject> includeItems = includedSchema.getItems();
for (XmlSchemaObject includedItem : includeItems) {
schemaItems.add(includedItem);
}
}
// remove the <include/>
schemaItems.remove(i);
i--;
}
}
}
private void findImports(XmlSchema schema, Set<XmlSchema> processedImports, Set<XmlSchema> processedIncludes) {
processedImports.add(schema);
List<XmlSchemaExternal> externals = schema.getExternals();
for (XmlSchemaExternal external : externals) {
if (external instanceof XmlSchemaImport) {
XmlSchemaImport schemaImport = (XmlSchemaImport) external;
XmlSchema importedSchema = schemaImport.getSchema();
if (!"http://www.w3.org/XML/1998/namespace".equals(schemaImport.getNamespace()) &&
importedSchema != null && !processedImports.contains(importedSchema)) {
inlineIncludes(importedSchema, processedIncludes, processedImports);
findImports(importedSchema, processedImports, processedIncludes);
xmlSchemas.add(importedSchema);
}
// remove the schemaLocation
external.setSchemaLocation(null);
}
}
}
private void findImports(XmlSchema schema, Set<XmlSchema> processedImports, Set<XmlSchema> processedIncludes) {
processedImports.add(schema);
List<XmlSchemaExternal> externals = schema.getExternals();
for (XmlSchemaExternal external : externals) {
if (external instanceof XmlSchemaImport) {
XmlSchemaImport schemaImport = (XmlSchemaImport) external;
XmlSchema importedSchema = schemaImport.getSchema();
if (!"http://www.w3.org/XML/1998/namespace".equals(schemaImport.getNamespace()) &&
importedSchema != null && !processedImports.contains(importedSchema)) {
inlineIncludes(importedSchema, processedIncludes, processedImports);
findImports(importedSchema, processedImports, processedIncludes);
xmlSchemas.add(importedSchema);
}
// remove the schemaLocation
external.setSchemaLocation(null);
}
}
}
public String toString() {
StringBuilder builder = new StringBuilder("CommonsXsdSchemaCollection");
builder.append('{');
for (int i = 0; i < xmlSchemas.size(); i++) {
XmlSchema schema = xmlSchemas.get(i);
builder.append(schema.getTargetNamespace());
if (i < xmlSchemas.size() - 1) {
builder.append(',');
}
}
builder.append('}');
return builder.toString();
}
public String toString() {
StringBuilder builder = new StringBuilder("CommonsXsdSchemaCollection");
builder.append('{');
for (int i = 0; i < xmlSchemas.size(); i++) {
XmlSchema schema = xmlSchemas.get(i);
builder.append(schema.getTargetNamespace());
if (i < xmlSchemas.size() - 1) {
builder.append(',');
}
}
builder.append('}');
return builder.toString();
}
private class ClasspathUriResolver extends DefaultURIResolver {
private class ClasspathUriResolver extends DefaultURIResolver {
@Override
public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) {
if (resourceLoader != null) {
Resource resource = resourceLoader.getResource(schemaLocation);
if (resource.exists()) {
return createInputSource(resource);
}
else if (StringUtils.hasLength(baseUri)) {
// let's try and find it relative to the baseUri, see SWS-413
try {
Resource baseUriResource = new UrlResource(baseUri);
resource = baseUriResource.createRelative(schemaLocation);
if (resource.exists()) {
return createInputSource(resource);
}
}
catch (IOException e) {
// fall through
}
}
// let's try and find it on the classpath, see SWS-362
String classpathLocation = ResourceLoader.CLASSPATH_URL_PREFIX + "/" + schemaLocation;
resource = resourceLoader.getResource(classpathLocation);
if (resource.exists()) {
return createInputSource(resource);
}
}
return super.resolveEntity(namespace, schemaLocation, baseUri);
}
@Override
public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) {
if (resourceLoader != null) {
Resource resource = resourceLoader.getResource(schemaLocation);
if (resource.exists()) {
return createInputSource(resource);
}
else if (StringUtils.hasLength(baseUri)) {
// let's try and find it relative to the baseUri, see SWS-413
try {
Resource baseUriResource = new UrlResource(baseUri);
resource = baseUriResource.createRelative(schemaLocation);
if (resource.exists()) {
return createInputSource(resource);
}
}
catch (IOException e) {
// fall through
}
}
// let's try and find it on the classpath, see SWS-362
String classpathLocation = ResourceLoader.CLASSPATH_URL_PREFIX + "/" + schemaLocation;
resource = resourceLoader.getResource(classpathLocation);
if (resource.exists()) {
return createInputSource(resource);
}
}
return super.resolveEntity(namespace, schemaLocation, baseUri);
}
private InputSource createInputSource(Resource resource) {
try {
return SaxUtils.createInputSource(resource);
}
catch (IOException ex) {
throw new CommonsXsdSchemaException("Could not resolve location", ex);
}
}
}
private InputSource createInputSource(Resource resource) {
try {
return SaxUtils.createInputSource(resource);
}
catch (IOException ex) {
throw new CommonsXsdSchemaException("Could not resolve location", ex);
}
}
}
}

View File

@@ -27,11 +27,11 @@ import org.springframework.xml.xsd.XsdSchemaException;
@SuppressWarnings("serial")
public class CommonsXsdSchemaException extends XsdSchemaException {
public CommonsXsdSchemaException(String message) {
super(message);
}
public CommonsXsdSchemaException(String message) {
super(message);
}
public CommonsXsdSchemaException(String message, Throwable exception) {
super(message, exception);
}
public CommonsXsdSchemaException(String message, Throwable exception) {
super(message, exception);
}
}