revised OXM package: no provider-specific exceptions anymore, etc

This commit is contained in:
Juergen Hoeller
2009-02-25 00:28:15 +00:00
parent 866ee1150e
commit 555fa3b4c8
71 changed files with 1535 additions and 2629 deletions

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2008 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,8 +31,7 @@ public abstract class Md5HashUtils {
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/** /**
* Calculates the MD5 hash of the given bytes. * Calculate the MD5 hash of the given bytes.
*
* @param bytes the bytes to calculate the hash over * @param bytes the bytes to calculate the hash over
* @return the hash * @return the hash
*/ */
@@ -59,8 +58,7 @@ public abstract class Md5HashUtils {
} }
/** /**
* Returns a hex string representation of the MD5 hash of the given bytes. * Return a hex string representation of the MD5 hash of the given bytes.
*
* @param bytes the bytes to calculate the hash over * @param bytes the bytes to calculate the hash over
* @return a hexadecimal hash string * @return a hexadecimal hash string
*/ */
@@ -69,9 +67,8 @@ public abstract class Md5HashUtils {
} }
/** /**
* Appends a hex string representation of the MD5 hash of the given bytes to the given {@link StringBuilder}. * Append a hex string representation of the MD5 hash of the given bytes to the given {@link StringBuilder}.
* * @param bytes the bytes to calculate the hash over
* @param bytes the bytes to calculate the hash over
* @param builder the string builder to append the hash to * @param builder the string builder to append the hash to
* @return the given string builder * @return the given string builder
*/ */

View File

@@ -34,11 +34,11 @@ import org.springframework.util.StringUtils;
* Abstract base class for SAX <code>XMLReader</code> implementations that use StAX as a basis. * Abstract base class for SAX <code>XMLReader</code> implementations that use StAX as a basis.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0
* @see #setContentHandler(org.xml.sax.ContentHandler) * @see #setContentHandler(org.xml.sax.ContentHandler)
* @see #setDTDHandler(org.xml.sax.DTDHandler) * @see #setDTDHandler(org.xml.sax.DTDHandler)
* @see #setEntityResolver(org.xml.sax.EntityResolver) * @see #setEntityResolver(org.xml.sax.EntityResolver)
* @see #setErrorHandler(org.xml.sax.ErrorHandler) * @see #setErrorHandler(org.xml.sax.ErrorHandler)
* @since 3.0
*/ */
abstract class AbstractStaxXMLReader extends AbstractXMLReader { abstract class AbstractStaxXMLReader extends AbstractXMLReader {
@@ -48,23 +48,25 @@ abstract class AbstractStaxXMLReader extends AbstractXMLReader {
private static final String IS_STANDALONE_FEATURE_NAME = "http://xml.org/sax/features/is-standalone"; private static final String IS_STANDALONE_FEATURE_NAME = "http://xml.org/sax/features/is-standalone";
private boolean namespacesFeature = true; private boolean namespacesFeature = true;
private boolean namespacePrefixesFeature = false; private boolean namespacePrefixesFeature = false;
private Boolean isStandalone; private Boolean isStandalone;
@Override @Override
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
if (NAMESPACES_FEATURE_NAME.equals(name)) { if (NAMESPACES_FEATURE_NAME.equals(name)) {
return namespacesFeature; return this.namespacesFeature;
} }
else if (NAMESPACE_PREFIXES_FEATURE_NAME.equals(name)) { else if (NAMESPACE_PREFIXES_FEATURE_NAME.equals(name)) {
return namespacePrefixesFeature; return this.namespacePrefixesFeature;
} }
else if (IS_STANDALONE_FEATURE_NAME.equals(name)) { else if (IS_STANDALONE_FEATURE_NAME.equals(name)) {
if (isStandalone != null) { if (this.isStandalone != null) {
return isStandalone; return this.isStandalone;
} }
else { else {
throw new SAXNotSupportedException("startDocument() callback not completed yet"); throw new SAXNotSupportedException("startDocument() callback not completed yet");
@@ -88,35 +90,66 @@ abstract class AbstractStaxXMLReader extends AbstractXMLReader {
} }
} }
/** Indicates whether the SAX feature <code>http://xml.org/sax/features/namespaces</code> is turned on. */
protected boolean hasNamespacesFeature() {
return namespacesFeature;
}
/** Indicates whether the SAX feature <code>http://xml.org/sax/features/namespaces-prefixes</code> is turned on. */
protected boolean hasNamespacePrefixesFeature() {
return namespacePrefixesFeature;
}
protected void setStandalone(boolean standalone) { protected void setStandalone(boolean standalone) {
isStandalone = (standalone) ? Boolean.TRUE : Boolean.FALSE; this.isStandalone = standalone;
} }
/** /**
* Parses the StAX XML reader passed at construction-time. <p/> <strong>Note</strong> that the given * Indicates whether the SAX feature <code>http://xml.org/sax/features/namespaces</code> is turned on.
* <code>InputSource</code> is not read, but ignored. */
* protected boolean hasNamespacesFeature() {
return this.namespacesFeature;
}
/**
* Indicates whether the SAX feature <code>http://xml.org/sax/features/namespaces-prefixes</code> is turned on.
*/
protected boolean hasNamespacePrefixesFeature() {
return this.namespacePrefixesFeature;
}
/**
* Sett the SAX <code>Locator</code> based on the given StAX <code>Location</code>.
* @param location the location
* @see ContentHandler#setDocumentLocator(org.xml.sax.Locator)
*/
protected void setLocator(Location location) {
if (getContentHandler() != null) {
getContentHandler().setDocumentLocator(new StaxLocator(location));
}
}
/**
* Convert a <code>QName</code> to a qualified name, as used by DOM and SAX.
* The returned string has a format of <code>prefix:localName</code> if the
* prefix is set, or just <code>localName</code> if not.
* @param qName the <code>QName</code>
* @return the qualified name
*/
protected String toQualifiedName(QName qName) {
String prefix = qName.getPrefix();
if (!StringUtils.hasLength(prefix)) {
return qName.getLocalPart();
}
else {
return prefix + ":" + qName.getLocalPart();
}
}
/**
* Parse the StAX XML reader passed at construction-time.
* <p><b>NOTE:</b>: The given <code>InputSource</code> is not read, but ignored.
* @param ignored is ignored * @param ignored is ignored
* @throws SAXException A SAX exception, possibly wrapping a <code>XMLStreamException</code> * @throws SAXException a SAX exception, possibly wrapping a <code>XMLStreamException</code>
*/ */
public final void parse(InputSource ignored) throws SAXException { public final void parse(InputSource ignored) throws SAXException {
parse(); parse();
} }
/** /**
* Parses the StAX XML reader passed at construction-time. <p/> <strong>Note</strong> that the given system identifier * Parse the StAX XML reader passed at construction-time.
* is not read, but ignored. * <p><b>NOTE:</b>: The given system identifier is not read, but ignored.
*
* @param ignored is ignored * @param ignored is ignored
* @throws SAXException A SAX exception, possibly wrapping a <code>XMLStreamException</code> * @throws SAXException A SAX exception, possibly wrapping a <code>XMLStreamException</code>
*/ */
@@ -144,40 +177,13 @@ abstract class AbstractStaxXMLReader extends AbstractXMLReader {
} }
/** /**
* Sets the SAX <code>Locator</code> based on the given StAX <code>Location</code>. * Template-method that parses the StAX reader passed at construction-time.
*
* @param location the location
* @see ContentHandler#setDocumentLocator(org.xml.sax.Locator)
*/ */
protected void setLocator(Location location) {
if (getContentHandler() != null) {
getContentHandler().setDocumentLocator(new StaxLocator(location));
}
}
/** Template-method that parses the StAX reader passed at construction-time. */
protected abstract void parseInternal() throws SAXException, XMLStreamException; protected abstract void parseInternal() throws SAXException, XMLStreamException;
/**
* Convert a <code>QName</code> to a qualified name, as used by DOM and SAX. The returned string has a format of
* <code>prefix:localName</code> if the prefix is set, or just <code>localName</code> if not.
*
* @param qName the <code>QName</code>
* @return the qualified name
*/
protected String toQualifiedName(QName qName) {
String prefix = qName.getPrefix();
if (!StringUtils.hasLength(prefix)) {
return qName.getLocalPart();
}
else {
return prefix + ":" + qName.getLocalPart();
}
}
/** /**
* Implementation of the <code>Locator</code> interface that is based on a StAX <code>Location</code>. * Implementation of the <code>Locator</code> interface that is based on a StAX <code>Location</code>.
*
* @see Locator * @see Locator
* @see Location * @see Location
*/ */
@@ -205,4 +211,5 @@ abstract class AbstractStaxXMLReader extends AbstractXMLReader {
return location.getColumnNumber(); return location.getColumnNumber();
} }
} }
} }

View File

@@ -1,89 +0,0 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util.xml;
import org.springframework.util.ClassUtils;
/**
* Helper class used to find the current version of JAXP. We cannot depend on the Java version, since JAXP can be
* upgraded independently of the Java version. <p/> Only distinguishes between JAXP 1.0, 1.1, 1.3, and 1.4, since JAXP
* 1.2 was a maintenance release with no new classes.
*
* @author Arjen Poutsma
* @since 3.0.0
*/
abstract class JaxpVersion {
public static final int JAXP_10 = 0;
public static final int JAXP_11 = 1;
public static final int JAXP_13 = 3;
public static final int JAXP_14 = 4;
private static final String JAXP_14_CLASS_NAME = "javax.xml.transform.stax.StAXSource";
private static int jaxpVersion;
static {
try {
ClassUtils.forName(JAXP_14_CLASS_NAME);
jaxpVersion = JAXP_14;
}
catch (ClassNotFoundException ignored) {
// default to JAXP 1.3, since Spring 3 requires JDK 1.5
jaxpVersion = JAXP_13;
}
}
/**
* Gets the JAXP version. This means we can do things like if <code>(getJaxpVersion() < JAXP_13)</code>.
*
* @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.3 (packaged with JDK 1.5).
*
* @return <code>true</code> if the current JAXP version is at least JAXP 1.3
* @see #getJaxpVersion()
* @see #JAXP_13
*/
public static boolean isAtLeastJaxp13() {
return getJaxpVersion() >= JAXP_13;
}
/**
* Convenience method to determine if the current JAXP version is at least 1.4 (packaged with JDK 1.6).
*
* @return <code>true</code> 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

@@ -30,27 +30,32 @@ import org.xml.sax.ContentHandler;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/** /**
* Convenience methods for working with the StAX API. * Convenience methods for working with the StAX API.
* *
* In particular, methods for using StAX in combination with the TrAX API (<code>javax.xml.transform</code>), and * <p>In particular, methods for using StAX in combination with the TrAX API
* converting StAX readers/writers into SAX readers/handlers and vice-versa. * (<code>javax.xml.transform</code>), and converting StAX readers/writers
* into SAX readers/handlers and vice-versa.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0 * @since 3.0
*/ */
public abstract class StaxUtils { public abstract class StaxUtils {
private static boolean jaxp14Available =
ClassUtils.isPresent("javax.xml.transform.stax.StAXSource", StaxUtils.class.getClassLoader());
/** /**
* Creates a StAX {@link Source} for the given {@link XMLStreamReader}. Returns a {@link StAXSource} under JAXP 1.4 or * Create a StAX {@link Source} for the given {@link XMLStreamReader}.
* higher, or a {@link StaxSource} otherwise.
*
* @param streamReader the StAX stream reader * @param streamReader the StAX stream reader
* @return a source wrapping <code>streamReader</code> * @return a source wrapping <code>streamReader</code>
*/ */
public static Source createStaxSource(XMLStreamReader streamReader) { public static Source createStaxSource(XMLStreamReader streamReader) {
if (JaxpVersion.isAtLeastJaxp14()) { if (jaxp14Available) {
return Jaxp14StaxHandler.createStaxSource(streamReader); return Jaxp14StaxHandler.createStaxSource(streamReader);
} }
else { else {
@@ -59,15 +64,13 @@ public abstract class StaxUtils {
} }
/** /**
* Creates a StAX {@link Source} for the given {@link XMLEventReader}. Returns a {@link StAXSource} under JAXP 1.4 or * Create a StAX {@link Source} for the given {@link XMLEventReader}.
* higher, or a {@link StaxSource} otherwise.
*
* @param eventReader the StAX event reader * @param eventReader the StAX event reader
* @return a source wrapping <code>streamReader</code> * @return a source wrapping <code>streamReader</code>
* @throws XMLStreamException in case of StAX errors * @throws XMLStreamException in case of StAX errors
*/ */
public static Source createStaxSource(XMLEventReader eventReader) throws XMLStreamException { public static Source createStaxSource(XMLEventReader eventReader) throws XMLStreamException {
if (JaxpVersion.isAtLeastJaxp14()) { if (jaxp14Available) {
return Jaxp14StaxHandler.createStaxSource(eventReader); return Jaxp14StaxHandler.createStaxSource(eventReader);
} }
else { else {
@@ -76,14 +79,21 @@ public abstract class StaxUtils {
} }
/** /**
* Creates a StAX {@link Result} for the given {@link XMLStreamWriter}. Returns a {@link StAXResult} under JAXP 1.4 or * Indicate whether the given {@link javax.xml.transform.Source} is a StAX Source.
* higher, or a {@link StaxResult} otherwise. * @return <code>true</code> if <code>source</code> is a Spring StaxSource or JAXP
* * 1.4 {@link javax.xml.transform.stax.StAXSource}; <code>false</code> otherwise.
*/
public static boolean isStaxSource(Source source) {
return (source instanceof StaxSource || (jaxp14Available && Jaxp14StaxHandler.isStaxSource(source)));
}
/**
* Create a StAX {@link Result} for the given {@link XMLStreamWriter}.
* @param streamWriter the StAX stream writer * @param streamWriter the StAX stream writer
* @return a result wrapping <code>streamWriter</code> * @return a result wrapping <code>streamWriter</code>
*/ */
public static Result createStaxResult(XMLStreamWriter streamWriter) { public static Result createStaxResult(XMLStreamWriter streamWriter) {
if (JaxpVersion.isAtLeastJaxp14()) { if (jaxp14Available) {
return Jaxp14StaxHandler.createStaxResult(streamWriter); return Jaxp14StaxHandler.createStaxResult(streamWriter);
} }
else { else {
@@ -92,15 +102,13 @@ public abstract class StaxUtils {
} }
/** /**
* Creates a StAX {@link Result} for the given {@link XMLEventWriter}. Returns a {@link StAXResult} under JAXP 1.4 or * Create a StAX {@link Result} for the given {@link XMLEventWriter}.
* higher, or a {@link StaxResult} otherwise.
*
* @param eventWriter the StAX event writer * @param eventWriter the StAX event writer
* @return a result wrapping <code>streamReader</code> * @return a result wrapping <code>streamReader</code>
* @throws XMLStreamException in case of StAX errors * @throws XMLStreamException in case of StAX errors
*/ */
public static Result createStaxResult(XMLEventWriter eventWriter) throws XMLStreamException { public static Result createStaxResult(XMLEventWriter eventWriter) throws XMLStreamException {
if (JaxpVersion.isAtLeastJaxp14()) { if (jaxp14Available) {
return Jaxp14StaxHandler.createStaxResult(eventWriter); return Jaxp14StaxHandler.createStaxResult(eventWriter);
} }
else { else {
@@ -109,54 +117,26 @@ public abstract class StaxUtils {
} }
/** /**
* Indicates whether the given {@link javax.xml.transform.Source} is a StAX Source. * Indicate whether the given {@link javax.xml.transform.Result} is a StAX Result.
* * @return <code>true</code> if <code>result</code> is a Spring StaxResult or JAXP
* @return <code>true</code> if <code>source</code> is a Spring {@link org.springframework.util.xml.StaxSource} or JAXP * 1.4 {@link javax.xml.transform.stax.StAXResult}; <code>false</code> otherwise.
* 1.4 {@link javax.xml.transform.stax.StAXSource}; <code>false</code> otherwise.
*/
public static boolean isStaxSource(Source source) {
if (source instanceof StaxSource) {
return true;
}
else if (JaxpVersion.isAtLeastJaxp14()) {
return Jaxp14StaxHandler.isStaxSource(source);
}
else {
return false;
}
}
/**
* Indicates whether the given {@link javax.xml.transform.Result} is a StAX Result.
*
* @return <code>true</code> if <code>result</code> is a Spring {@link org.springframework.util.xml.StaxResult} or JAXP
* 1.4 {@link javax.xml.transform.stax.StAXResult}; <code>false</code> otherwise.
*/ */
public static boolean isStaxResult(Result result) { public static boolean isStaxResult(Result result) {
if (result instanceof StaxResult) { return (result instanceof StaxResult || (jaxp14Available && Jaxp14StaxHandler.isStaxResult(result)));
return true;
}
else if (JaxpVersion.isAtLeastJaxp14()) {
return Jaxp14StaxHandler.isStaxResult(result);
}
else {
return false;
}
} }
/** /**
* Returns the {@link javax.xml.stream.XMLStreamReader} for the given StAX Source. * Return the {@link javax.xml.stream.XMLStreamReader} for the given StAX Source.
* * @param source a Spring StaxSource or JAXP 1.4 {@link javax.xml.transform.stax.StAXSource}
* @param source a Spring {@link org.springframework.util.xml.StaxSource} or {@link javax.xml.transform.stax.StAXSource}
* @return the {@link javax.xml.stream.XMLStreamReader} * @return the {@link javax.xml.stream.XMLStreamReader}
* @throws IllegalArgumentException if <code>source</code> is neither a Spring-WS {@link org.springframework.util.xml.StaxSource} * @throws IllegalArgumentException if <code>source</code> is neither a Spring StaxSource
* or {@link javax.xml.transform.stax.StAXSource} * nor JAXP 1.4 {@link javax.xml.transform.stax.StAXSource}
*/ */
public static XMLStreamReader getXMLStreamReader(Source source) { public static XMLStreamReader getXMLStreamReader(Source source) {
if (source instanceof StaxSource) { if (source instanceof StaxSource) {
return ((StaxSource) source).getXMLStreamReader(); return ((StaxSource) source).getXMLStreamReader();
} }
else if (JaxpVersion.isAtLeastJaxp14()) { else if (jaxp14Available) {
return Jaxp14StaxHandler.getXMLStreamReader(source); return Jaxp14StaxHandler.getXMLStreamReader(source);
} }
else { else {
@@ -165,18 +145,17 @@ public abstract class StaxUtils {
} }
/** /**
* Returns the {@link javax.xml.stream.XMLEventReader} for the given StAX Source. * Return the {@link javax.xml.stream.XMLEventReader} for the given StAX Source.
* * @param source a Spring StaxSource or JAXP 1.4 {@link javax.xml.transform.stax.StAXSource}
* @param source a Spring {@link org.springframework.util.xml.StaxSource} or {@link javax.xml.transform.stax.StAXSource}
* @return the {@link javax.xml.stream.XMLEventReader} * @return the {@link javax.xml.stream.XMLEventReader}
* @throws IllegalArgumentException if <code>source</code> is neither a Spring {@link org.springframework.util.xml.StaxSource} * @throws IllegalArgumentException if <code>source</code> is neither a Spring StaxSource
* or {@link javax.xml.transform.stax.StAXSource} * nor a JAXP 1.4 {@link javax.xml.transform.stax.StAXSource}
*/ */
public static XMLEventReader getXMLEventReader(Source source) { public static XMLEventReader getXMLEventReader(Source source) {
if (source instanceof StaxSource) { if (source instanceof StaxSource) {
return ((StaxSource) source).getXMLEventReader(); return ((StaxSource) source).getXMLEventReader();
} }
else if (JaxpVersion.isAtLeastJaxp14()) { else if (jaxp14Available) {
return Jaxp14StaxHandler.getXMLEventReader(source); return Jaxp14StaxHandler.getXMLEventReader(source);
} }
else { else {
@@ -185,18 +164,17 @@ public abstract class StaxUtils {
} }
/** /**
* Returns the {@link javax.xml.stream.XMLStreamWriter} for the given StAX Result. * Return the {@link javax.xml.stream.XMLStreamWriter} for the given StAX Result.
* * @param result a Spring StaxResult or JAXP 1.4 {@link javax.xml.transform.stax.StAXResult}
* @param result a Spring {@link org.springframework.util.xml.StaxResult} or {@link javax.xml.transform.stax.StAXResult}
* @return the {@link javax.xml.stream.XMLStreamReader} * @return the {@link javax.xml.stream.XMLStreamReader}
* @throws IllegalArgumentException if <code>source</code> is neither a Spring {@link org.springframework.util.xml.StaxResult} * @throws IllegalArgumentException if <code>source</code> is neither a Spring StaxResult
* or {@link javax.xml.transform.stax.StAXResult} * nor a JAXP 1.4 {@link javax.xml.transform.stax.StAXResult}
*/ */
public static XMLStreamWriter getXMLStreamWriter(Result result) { public static XMLStreamWriter getXMLStreamWriter(Result result) {
if (result instanceof StaxResult) { if (result instanceof StaxResult) {
return ((StaxResult) result).getXMLStreamWriter(); return ((StaxResult) result).getXMLStreamWriter();
} }
else if (JaxpVersion.isAtLeastJaxp14()) { else if (jaxp14Available) {
return Jaxp14StaxHandler.getXMLStreamWriter(result); return Jaxp14StaxHandler.getXMLStreamWriter(result);
} }
else { else {
@@ -205,18 +183,17 @@ public abstract class StaxUtils {
} }
/** /**
* Returns the {@link XMLEventWriter} for the given StAX Result. * Return the {@link XMLEventWriter} for the given StAX Result.
* * @param result a Spring StaxResult or JAXP 1.4 {@link javax.xml.transform.stax.StAXResult}
* @param result a Spring {@link org.springframework.util.xml.StaxResult} or {@link javax.xml.transform.stax.StAXResult}
* @return the {@link javax.xml.stream.XMLStreamReader} * @return the {@link javax.xml.stream.XMLStreamReader}
* @throws IllegalArgumentException if <code>source</code> is neither a Spring {@link org.springframework.util.xml.StaxResult} * @throws IllegalArgumentException if <code>source</code> is neither a Spring StaxResult
* or {@link javax.xml.transform.stax.StAXResult} * nor a JAXP 1.4 {@link javax.xml.transform.stax.StAXResult}
*/ */
public static XMLEventWriter getXMLEventWriter(Result result) { public static XMLEventWriter getXMLEventWriter(Result result) {
if (result instanceof StaxResult) { if (result instanceof StaxResult) {
return ((StaxResult) result).getXMLEventWriter(); return ((StaxResult) result).getXMLEventWriter();
} }
else if (JaxpVersion.isAtLeastJaxp14()) { else if (jaxp14Available) {
return Jaxp14StaxHandler.getXMLEventWriter(result); return Jaxp14StaxHandler.getXMLEventWriter(result);
} }
else { else {
@@ -225,8 +202,7 @@ public abstract class StaxUtils {
} }
/** /**
* Creates a SAX {@link ContentHandler} that writes to the given StAX {@link XMLStreamWriter}. * Create a SAX {@link ContentHandler} that writes to the given StAX {@link XMLStreamWriter}.
*
* @param streamWriter the StAX stream writer * @param streamWriter the StAX stream writer
* @return a content handler writing to the <code>streamWriter</code> * @return a content handler writing to the <code>streamWriter</code>
*/ */
@@ -235,8 +211,7 @@ public abstract class StaxUtils {
} }
/** /**
* Creates a SAX {@link ContentHandler} that writes events to the given StAX {@link XMLEventWriter}. * Create a SAX {@link ContentHandler} that writes events to the given StAX {@link XMLEventWriter}.
*
* @param eventWriter the StAX event writer * @param eventWriter the StAX event writer
* @return a content handler writing to the <code>eventWriter</code> * @return a content handler writing to the <code>eventWriter</code>
*/ */
@@ -245,8 +220,7 @@ public abstract class StaxUtils {
} }
/** /**
* Creates a SAX {@link XMLReader} that reads from the given StAX {@link XMLStreamReader}. * Create a SAX {@link XMLReader} that reads from the given StAX {@link XMLStreamReader}.
*
* @param streamReader the StAX stream reader * @param streamReader the StAX stream reader
* @return a XMLReader reading from the <code>streamWriter</code> * @return a XMLReader reading from the <code>streamWriter</code>
*/ */
@@ -255,8 +229,7 @@ public abstract class StaxUtils {
} }
/** /**
* Creates a SAX {@link XMLReader} that reads from the given StAX {@link XMLEventReader}. * Create a SAX {@link XMLReader} that reads from the given StAX {@link XMLEventReader}.
*
* @param eventReader the StAX event reader * @param eventReader the StAX event reader
* @return a XMLReader reading from the <code>eventWriter</code> * @return a XMLReader reading from the <code>eventWriter</code>
*/ */
@@ -265,16 +238,18 @@ public abstract class StaxUtils {
} }
/** /**
* Returns a {@link XMLStreamReader} that reads from a {@link XMLEventReader}. Useful, because the StAX * Return a {@link XMLStreamReader} that reads from a {@link XMLEventReader}. Useful, because the StAX
* <code>XMLInputFactory</code> allows one to create a event reader from a stream reader, but not vice-versa. * <code>XMLInputFactory</code> allows one to create a event reader from a stream reader, but not vice-versa.
*
* @return a stream reader that reads from an event reader * @return a stream reader that reads from an event reader
*/ */
public static XMLStreamReader createEventStreamReader(XMLEventReader eventReader) throws XMLStreamException { public static XMLStreamReader createEventStreamReader(XMLEventReader eventReader) throws XMLStreamException {
return new XMLEventStreamReader(eventReader); return new XMLEventStreamReader(eventReader);
} }
/** Inner class to avoid a static JAXP 1.4 dependency. */
/**
* Inner class to avoid a static JAXP 1.4 dependency.
*/
private static class Jaxp14StaxHandler { private static class Jaxp14StaxHandler {
private static Source createStaxSource(XMLStreamReader streamReader) { private static Source createStaxSource(XMLStreamReader streamReader) {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2007 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -33,57 +33,54 @@ import javax.xml.transform.stream.StreamSource;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.oxm.Marshaller; import org.springframework.oxm.Marshaller;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.UnmarshallingFailureException; import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* Spring JMS {@link MessageConverter} that uses a {@link Marshaller} and {@link Unmarshaller}. Marshals an object to a * Spring JMS {@link MessageConverter} that uses a {@link Marshaller} and {@link Unmarshaller}.
* {@link BytesMessage}, or to a {@link TextMessage} if the {@link #setMarshalTo marshalTo} is set to {@link * Marshals an object to a {@link BytesMessage}, or to a {@link TextMessage} if the
* #MARSHAL_TO_TEXT_MESSAGE}. Unmarshals from a {@link TextMessage} or {@link BytesMessage} to an object. * {@link #setTargetType marshalTo} is set to {@link MessageType#TEXT}.
* Unmarshals from a {@link TextMessage} or {@link BytesMessage} to an object.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.jms.core.JmsTemplate#convertAndSend * @see org.springframework.jms.core.JmsTemplate#convertAndSend
* @see org.springframework.jms.core.JmsTemplate#receiveAndConvert * @see org.springframework.jms.core.JmsTemplate#receiveAndConvert
* @since 3.0
*/ */
public class MarshallingMessageConverter implements MessageConverter, InitializingBean { public class MarshallingMessageConverter implements MessageConverter, InitializingBean {
/** Constant that indicates that {@link #toMessage(Object, Session)} should marshal to a {@link BytesMessage}. */
public static final int MARSHAL_TO_BYTES_MESSAGE = 1;
/** Constant that indicates that {@link #toMessage(Object, Session)} should marshal to a {@link TextMessage}. */
public static final int MARSHAL_TO_TEXT_MESSAGE = 2;
private Marshaller marshaller; private Marshaller marshaller;
private Unmarshaller unmarshaller; private Unmarshaller unmarshaller;
private int marshalTo = MARSHAL_TO_BYTES_MESSAGE; private MessageType targetType = MessageType.BYTES;
/** /**
* Constructs a new <code>MarshallingMessageConverter</code> with no {@link Marshaller} set. The marshaller must be set * Construct a new <code>MarshallingMessageConverter</code> with no {@link Marshaller} set.
* after construction by invoking {@link #setMarshaller(Marshaller)}. * The marshaller must be set after construction by invoking {@link #setMarshaller(Marshaller)}.
*/ */
public MarshallingMessageConverter() { public MarshallingMessageConverter() {
} }
/** /**
* Constructs a new <code>MarshallingMessageConverter</code> with the given {@link Marshaller} set. If the given * Construct a new <code>MarshallingMessageConverter</code> with the given {@link Marshaller} set.
* {@link Marshaller} also implements the {@link Unmarshaller} interface, it is used for both marshalling and * <p>If the given {@link Marshaller} also implements the {@link Unmarshaller} interface,
* unmarshalling. Otherwise, an exception is thrown. <p/> Note that all {@link Marshaller} implementations in Spring-WS * it is used for both marshalling and unmarshalling. Otherwise, an exception is thrown.
* also implement the {@link Unmarshaller} interface, so that you can safely use this constructor. * <p>Note that all {@link Marshaller} implementations in Spring also implement the
* * {@link Unmarshaller} interface, so that you can safely use this constructor.
* @param marshaller object used as marshaller and unmarshaller * @param marshaller object used as marshaller and unmarshaller
* @throws IllegalArgumentException when <code>marshaller</code> does not implement the {@link Unmarshaller} interface * @throws IllegalArgumentException when <code>marshaller</code> does not implement the
* {@link Unmarshaller} interface as well
*/ */
public MarshallingMessageConverter(Marshaller marshaller) { public MarshallingMessageConverter(Marshaller marshaller) {
Assert.notNull(marshaller, "marshaller must not be null"); Assert.notNull(marshaller, "marshaller must not be null");
if (!(marshaller instanceof Unmarshaller)) { if (!(marshaller instanceof Unmarshaller)) {
throw new IllegalArgumentException("Marshaller [" + marshaller + "] does not implement the Unmarshaller " + throw new IllegalArgumentException(
"Marshaller [" + marshaller + "] does not implement the Unmarshaller " +
"interface. Please set an Unmarshaller explicitely by using the " + "interface. Please set an Unmarshaller explicitely by using the " +
"AbstractMarshallingPayloadEndpoint(Marshaller, Unmarshaller) constructor."); "MarshallingMessageConverter(Marshaller, Unmarshaller) constructor.");
} }
else { else {
this.marshaller = marshaller; this.marshaller = marshaller;
@@ -92,10 +89,10 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
} }
/** /**
* Creates a new <code>MarshallingMessageConverter</code> with the given marshaller and unmarshaller. * Construct a new <code>MarshallingMessageConverter</code> with the
* * given Marshaller and Unmarshaller.
* @param marshaller the marshaller to use * @param marshaller the Marshaller to use
* @param unmarshaller the unmarshaller to use * @param unmarshaller the Unmarshaller to use
*/ */
public MarshallingMessageConverter(Marshaller marshaller, Unmarshaller unmarshaller) { public MarshallingMessageConverter(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null"); Assert.notNull(marshaller, "marshaller must not be null");
@@ -104,52 +101,59 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
this.unmarshaller = unmarshaller; this.unmarshaller = unmarshaller;
} }
/**
* Indicates whether {@link #toMessage(Object,Session)} should marshal to a {@link BytesMessage} or a {@link
* TextMessage}. The default is {@link #MARSHAL_TO_BYTES_MESSAGE}, i.e. this converter marshals to a {@link
* BytesMessage}.
*
* @see #MARSHAL_TO_BYTES_MESSAGE
* @see #MARSHAL_TO_TEXT_MESSAGE
*/
public void setMarshalTo(int marshalTo) {
this.marshalTo = marshalTo;
}
/** Sets the {@link Marshaller} to be used by this message converter. */ /**
* Set the {@link Marshaller} to be used by this message converter.
*/
public void setMarshaller(Marshaller marshaller) { public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller; this.marshaller = marshaller;
} }
/** Sets the {@link Unmarshaller} to be used by this message converter. */ /**
* Set the {@link Unmarshaller} to be used by this message converter.
*/
public void setUnmarshaller(Unmarshaller unmarshaller) { public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller; this.unmarshaller = unmarshaller;
} }
public void afterPropertiesSet() throws Exception { /**
Assert.notNull(marshaller, "Property 'marshaller' is required"); * Specify whether {@link #toMessage(Object, Session)} should marshal to
Assert.notNull(unmarshaller, "Property 'unmarshaller' is required"); * a {@link BytesMessage} or a {@link TextMessage}.
* <p>The default is {@link MessageType#BYTES}, i.e. this converter marshals
* to a {@link BytesMessage}. Note that the default version of this converter
* supports {@link MessageType#BYTES} and {@link MessageType#TEXT} only.
* @see MessageType#BYTES
* @see MessageType#TEXT
*/
public void setTargetType(MessageType targetType) {
this.targetType = targetType;
} }
public void afterPropertiesSet() {
Assert.notNull(this.marshaller, "Property 'marshaller' is required");
Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
}
/** /**
* Marshals the given object to a {@link TextMessage} or {@link javax.jms.BytesMessage}. The desired message type can * This implementation marshals the given object to a {@link javax.jms.TextMessage} or
* be defined by setting the {@link #setMarshalTo(int) marshalTo} property. * {@link javax.jms.BytesMessage}. The desired message type can be defined by setting
* * the {@link #setTargetType "marshalTo"} property.
* @see #marshalToTextMessage * @see #marshalToTextMessage
* @see #marshalToBytesMessage * @see #marshalToBytesMessage
*/ */
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
try { try {
switch (marshalTo) { switch (this.targetType) {
case MARSHAL_TO_TEXT_MESSAGE: case TEXT:
return marshalToTextMessage(object, session, marshaller); return marshalToTextMessage(object, session, this.marshaller);
case MARSHAL_TO_BYTES_MESSAGE: case BYTES:
return marshalToBytesMessage(object, session, marshaller); return marshalToBytesMessage(object, session, this.marshaller);
default: default:
return marshalToMessage(object, session, marshaller); return marshalToMessage(object, session, this.marshaller, this.targetType);
} }
} }
catch (MarshallingFailureException ex) { catch (XmlMappingException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex); throw new MessageConversionException("Could not marshal [" + object + "]", ex);
} }
catch (IOException ex) { catch (IOException ex) {
@@ -158,8 +162,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
} }
/** /**
* Unmarshals the given {@link Message} into an object. * This implementation unmarshals the given {@link Message} into an object.
*
* @see #unmarshalFromTextMessage * @see #unmarshalFromTextMessage
* @see #unmarshalFromBytesMessage * @see #unmarshalFromBytesMessage
*/ */
@@ -167,38 +170,40 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
try { try {
if (message instanceof TextMessage) { if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message; TextMessage textMessage = (TextMessage) message;
return unmarshalFromTextMessage(textMessage, unmarshaller); return unmarshalFromTextMessage(textMessage, this.unmarshaller);
} }
else if (message instanceof BytesMessage) { else if (message instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) message; BytesMessage bytesMessage = (BytesMessage) message;
return unmarshalFromBytesMessage(bytesMessage, unmarshaller); return unmarshalFromBytesMessage(bytesMessage, this.unmarshaller);
} }
else { else {
return unmarshalFromMessage(message, unmarshaller); return unmarshalFromMessage(message, this.unmarshaller);
} }
} }
catch (UnmarshallingFailureException ex) {
throw new MessageConversionException("Could not unmarshal message [" + message + "]", ex);
}
catch (IOException ex) { catch (IOException ex) {
throw new MessageConversionException("Could not unmarshal message [" + message + "]", ex); throw new MessageConversionException("Could not access message content: " + message, ex);
}
catch (XmlMappingException ex) {
throw new MessageConversionException("Could not unmarshal message: " + message, ex);
} }
} }
/** /**
* Marshals the given object to a {@link TextMessage}. * Marshal the given object to a {@link TextMessage}.
* * @param object the object to be marshalled
* @param object the object to be marshalled * @param session current JMS session
* @param session current JMS session
* @param marshaller the marshaller to use * @param marshaller the marshaller to use
* @return the resulting message * @return the resulting message
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @throws XmlMappingException in case of OXM mapping errors
* @see Session#createTextMessage * @see Session#createTextMessage
* @see Marshaller#marshal(Object, Result) * @see Marshaller#marshal(Object, Result)
*/ */
protected TextMessage marshalToTextMessage(Object object, Session session, Marshaller marshaller) protected TextMessage marshalToTextMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException { throws JMSException, IOException, XmlMappingException {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
Result result = new StreamResult(writer); Result result = new StreamResult(writer);
marshaller.marshal(object, result); marshaller.marshal(object, result);
@@ -206,19 +211,20 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
} }
/** /**
* Marshals the given object to a {@link BytesMessage}. * Marshal the given object to a {@link BytesMessage}.
* * @param object the object to be marshalled
* @param object the object to be marshalled * @param session current JMS session
* @param session current JMS session
* @param marshaller the marshaller to use * @param marshaller the marshaller to use
* @return the resulting message * @return the resulting message
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @throws XmlMappingException in case of OXM mapping errors
* @see Session#createBytesMessage * @see Session#createBytesMessage
* @see Marshaller#marshal(Object, Result) * @see Marshaller#marshal(Object, Result)
*/ */
protected BytesMessage marshalToBytesMessage(Object object, Session session, Marshaller marshaller) protected BytesMessage marshalToBytesMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException { throws JMSException, IOException, XmlMappingException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult(bos); StreamResult streamResult = new StreamResult(bos);
marshaller.marshal(object, streamResult); marshaller.marshal(object, streamResult);
@@ -228,51 +234,57 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
} }
/** /**
* Template method that allows for custom message marshalling. Invoked when {@link #setMarshalTo(int)} is not {@link * Template method that allows for custom message marshalling.
* #MARSHAL_TO_TEXT_MESSAGE} or {@link #MARSHAL_TO_BYTES_MESSAGE}. <p/> Default implemenetation throws a {@link * Invoked when {@link #setTargetType} is not {@link MessageType#TEXT} or
* MessageConversionException}. * {@link MessageType#BYTES}.
* * <p>The default implementation throws an {@link IllegalArgumentException}.
* @param object the object to marshal * @param object the object to marshal
* @param session the JMS session * @param session the JMS session
* @param marshaller the marshaller to use * @param marshaller the marshaller to use
* @param targetType the target message type (other than TEXT or BYTES)
* @return the resulting message * @return the resulting message
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @throws XmlMappingException in case of OXM mapping errors
*/ */
protected Message marshalToMessage(Object object, Session session, Marshaller marshaller) protected Message marshalToMessage(Object object, Session session, Marshaller marshaller, MessageType targetType)
throws JMSException, IOException { throws JMSException, IOException, XmlMappingException {
throw new MessageConversionException(
"Unknown 'marshalTo' value [" + marshalTo + "]. Cannot convert object to Message"); throw new IllegalArgumentException(
"Unsupported message type [" + targetType + "]. Cannot marshal to the specified message type.");
} }
/** /**
* Unmarshals the given {@link TextMessage} into an object. * Unmarshal the given {@link TextMessage} into an object.
* * @param message the message
* @param message the message
* @param unmarshaller the unmarshaller to use * @param unmarshaller the unmarshaller to use
* @return the unmarshalled object * @return the unmarshalled object
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @throws XmlMappingException in case of OXM mapping errors
* @see Unmarshaller#unmarshal(Source) * @see Unmarshaller#unmarshal(Source)
*/ */
protected Object unmarshalFromTextMessage(TextMessage message, Unmarshaller unmarshaller) protected Object unmarshalFromTextMessage(TextMessage message, Unmarshaller unmarshaller)
throws JMSException, IOException { throws JMSException, IOException, XmlMappingException {
Source source = new StreamSource(new StringReader(message.getText())); Source source = new StreamSource(new StringReader(message.getText()));
return unmarshaller.unmarshal(source); return unmarshaller.unmarshal(source);
} }
/** /**
* Unmarshals the given {@link BytesMessage} into an object. * Unmarshal the given {@link BytesMessage} into an object.
* * @param message the message
* @param message the message
* @param unmarshaller the unmarshaller to use * @param unmarshaller the unmarshaller to use
* @return the unmarshalled object * @return the unmarshalled object
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @throws XmlMappingException in case of OXM mapping errors
* @see Unmarshaller#unmarshal(Source) * @see Unmarshaller#unmarshal(Source)
*/ */
protected Object unmarshalFromBytesMessage(BytesMessage message, Unmarshaller unmarshaller) protected Object unmarshalFromBytesMessage(BytesMessage message, Unmarshaller unmarshaller)
throws JMSException, IOException { throws JMSException, IOException, XmlMappingException {
byte[] bytes = new byte[(int) message.getBodyLength()]; byte[] bytes = new byte[(int) message.getBodyLength()];
message.readBytes(bytes); message.readBytes(bytes);
ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
@@ -281,19 +293,22 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
} }
/** /**
* Template method that allows for custom message unmarshalling. Invoked when {@link #fromMessage(Message)} is invoked * Template method that allows for custom message unmarshalling.
* with a message that is not a {@link TextMessage} or {@link BytesMessage}. <p/> Default implemenetation throws a * Invoked when {@link #fromMessage(Message)} is invoked with a message
* {@link MessageConversionException}. * that is not a {@link TextMessage} or {@link BytesMessage}.
* * <p>The default implemenetation throws an {@link IllegalArgumentException}.
* @param message the message * @param message the message
* @param unmarshaller the unmarshaller to use * @param unmarshaller the unmarshaller to use
* @return the unmarshalled object * @return the unmarshalled object
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @throws XmlMappingException in case of OXM mapping errors
*/ */
protected Object unmarshalFromMessage(Message message, Unmarshaller unmarshaller) throws JMSException, IOException { protected Object unmarshalFromMessage(Message message, Unmarshaller unmarshaller)
throw new MessageConversionException( throws JMSException, IOException, XmlMappingException {
throw new IllegalArgumentException(
"MarshallingMessageConverter only supports TextMessages and BytesMessages"); "MarshallingMessageConverter only supports TextMessages and BytesMessages");
} }
}
}

View File

@@ -1,32 +1,32 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.castor;
package org.springframework.jms.support.converter;
import org.springframework.oxm.UncategorizedXmlMappingException;
/**
/** * Constants that indicate a target message type to convert to: a
* Castor-specific subclass of <code>UncategorizedXmlMappingException</code>, for Castor exceptions that cannot be * {@link javax.jms.TextMessage}, a {@link javax.jms.BytesMessage},
* distinguished further. * a {@link javax.jms.MapMessage} or an {@link ObjectMessage}.
* *
* @author Arjen Poutsma * @author Juergen Hoeller
* @since 3.0 * @since 3.0
*/ * @see MarshallingMessageConverter#setTargetType
public class CastorSystemException extends UncategorizedXmlMappingException { */
public enum MessageType {
public CastorSystemException(String msg, Throwable ex) {
super(msg, ex); TEXT, BYTES, MAP, OBJECT
}
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2007 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,13 +23,16 @@ import javax.xml.transform.Result;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import static org.easymock.EasyMock.*; import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.oxm.Marshaller; import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.Unmarshaller;
/**
* @author Arjen Poutsma
*/
public class MarshallingMessageConverterTests { public class MarshallingMessageConverterTests {
private MarshallingMessageConverter converter; private MarshallingMessageConverter converter;
@@ -83,7 +86,7 @@ public class MarshallingMessageConverterTests {
@Test @Test
public void toTextMessage() throws Exception { public void toTextMessage() throws Exception {
converter.setMarshalTo(MarshallingMessageConverter.MARSHAL_TO_TEXT_MESSAGE); converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = createMock(TextMessage.class); TextMessage textMessageMock = createMock(TextMessage.class);
Object toBeMarshalled = new Object(); Object toBeMarshalled = new Object();
@@ -114,4 +117,4 @@ public class MarshallingMessageConverterTests {
verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,39 +13,42 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
import java.io.IOException; import java.io.IOException;
import javax.xml.transform.Result; import javax.xml.transform.Result;
/** /**
* Defines the contract for Object XML Mapping Marshallers. Implementations of this interface can serialize a given * Defines the contract for Object XML Mapping Marshallers. Implementations of this interface
* Object to an XML Stream. <p/> Although the <code>marshal</code> method accepts a <code>java.lang.Object</code> as its * can serialize a given Object to an XML Stream.
* first parameter, most <code>Marshaller</code> implementations cannot handle arbitrary <code>java.lang.Object</code>. *
* Instead, a object class must be registered with the marshaller, or have a common base class. * <p>Although the <code>marshal</code> method accepts a <code>java.lang.Object</code> as its
* first parameter, most <code>Marshaller</code> implementations cannot handle arbitrary
* <code>Object</code>s. Instead, a object class must be registered with the marshaller,
* or have a common base class.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
* @see Unmarshaller
*/ */
public interface Marshaller { public interface Marshaller {
/**
* Marshals the object graph with the given root into the provided {@link Result}.
*
* @param graph the root of the object graph to marshal
* @param result the result to marshal to
* @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IOException if an I/O exception occurs
*/
void marshal(Object graph, Result result) throws XmlMappingException, IOException;
/** /**
* Indicates whether this marshaller can marshal instances of the supplied type. * Indicates whether this marshaller can marshal instances of the supplied type.
*
* @param clazz the class that this marshaller is being asked if it can marshal * @param clazz the class that this marshaller is being asked if it can marshal
* @return <code>true</code> if this marshaller can indeed marshal instances of the supplied class; <code>false</code> * @return <code>true</code> if this marshaller can indeed marshal instances of the supplied class;
* otherwise * <code>false</code> otherwise
*/ */
boolean supports(Class<?> clazz); boolean supports(Class<?> clazz);
/**
* Marshals the object graph with the given root into the provided {@link Result}.
* @param graph the root of the object graph to marshal
* @param result the result to marshal to
* @throws IOException if an I/O error occurs
* @throws XmlMappingException if the given object cannot be marshalled to the result
*/
void marshal(Object graph, Result result) throws IOException, XmlMappingException;
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,26 +13,36 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
/** /**
* Base class for exception thrown when a marshalling or unmarshalling error occurs. * Base class for exception thrown when a marshalling or unmarshalling error occurs.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see MarshallingFailureException * @see MarshallingFailureException
* @see UnmarshallingFailureException * @see UnmarshallingFailureException
* @since 3.0
*/ */
public abstract class GenericMarshallingFailureException extends XmlMappingException { public abstract class MarshallingException extends XmlMappingException {
/** Constructor for <code>GenericMarshallingFailureException</code>. */ /**
public GenericMarshallingFailureException(String msg) { * Construct a <code>MarshallingException</code> with the specified detail message.
* @param msg the detail message
*/
protected MarshallingException(String msg) {
super(msg); super(msg);
} }
/** Constructor for <code>GenericMarshallingFailureException</code>. */ /**
public GenericMarshallingFailureException(String msg, Throwable ex) { * Construct a <code>MarshallingException</code> with the specified detail message
super(msg, ex); * and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
protected MarshallingException(String msg, Throwable cause) {
super(msg, cause);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
/** /**
@@ -21,11 +22,10 @@ package org.springframework.oxm;
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
*/ */
public class MarshallingFailureException extends GenericMarshallingFailureException { public class MarshallingFailureException extends MarshallingException {
/** /**
* Construct a <code>MarshallingFailureException</code> with the specified detail message. * Construct a <code>MarshallingFailureException</code> with the specified detail message.
*
* @param msg the detail message * @param msg the detail message
*/ */
public MarshallingFailureException(String msg) { public MarshallingFailureException(String msg) {
@@ -33,12 +33,13 @@ public class MarshallingFailureException extends GenericMarshallingFailureExcept
} }
/** /**
* Construct a <code>MarshallingFailureException</code> with the specified detail message and nested exception. * Construct a <code>MarshallingFailureException</code> with the specified detail message
* * and nested exception.
* @param msg the detail message * @param msg the detail message
* @param ex the nested exception * @param cause the nested exception
*/ */
public MarshallingFailureException(String msg, Throwable ex) { public MarshallingFailureException(String msg, Throwable cause) {
super(msg, ex); super(msg, cause);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,18 +13,25 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
/** /**
* Superclass for exceptions that cannot be distinguished further. * Exception that indicates that the cause cannot be distinguished further.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
*/ */
public abstract class UncategorizedXmlMappingException extends XmlMappingException { public class UncategorizedMappingException extends XmlMappingException {
/** Constructor for <code>UncategorizedXmlMappingException</code>. */ /**
protected UncategorizedXmlMappingException(String msg, Throwable ex) { * Construct an <code>UncategorizedMappingException</code> with the specified detail message
super(msg, ex); * and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
public UncategorizedMappingException(String msg, Throwable cause) {
super(msg, cause);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005-2007 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,37 +13,37 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
import java.io.IOException; import java.io.IOException;
import javax.xml.transform.Source; import javax.xml.transform.Source;
/** /**
* Defines the contract for Object XML Mapping unmarshallers. <p/> <p>Implementations of this interface can deserialize * Defines the contract for Object XML Mapping unmarshallers. Implementations of this
* a given XML Stream to an Object graph. * interface can deserialize a given XML Stream to an Object graph.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
* @see Marshaller
*/ */
public interface Unmarshaller { public interface Unmarshaller {
/**
* Unmarshals the given {@link Source} into an object graph.
*
* @param source the source to marshal from
* @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IOException if an I/O Exception occurs
*/
Object unmarshal(Source source) throws XmlMappingException, IOException;
/** /**
* Indicates whether this unmarshaller can unmarshal instances of the supplied type. * Indicates whether this unmarshaller can unmarshal instances of the supplied type.
*
* @param clazz the class that this unmarshaller is being asked if it can marshal * @param clazz the class that this unmarshaller is being asked if it can marshal
* @return <code>true</code> if this unmarshaller can indeed unmarshal to the supplied class; <code>false</code> * @return <code>true</code> if this unmarshaller can indeed unmarshal to the supplied class;
* otherwise * <code>false</code> otherwise
*/ */
boolean supports(Class<?> clazz); boolean supports(Class<?> clazz);
/**
* Unmarshals the given {@link Source} into an object graph.
* @param source the source to marshal from
* @return the object graph
* @throws IOException if an I/O error occurs
* @throws XmlMappingException if the given source cannot be mapped to an object
*/
Object unmarshal(Source source) throws IOException, XmlMappingException;
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
/** /**
@@ -21,15 +22,24 @@ package org.springframework.oxm;
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
*/ */
public class UnmarshallingFailureException extends GenericMarshallingFailureException { public class UnmarshallingFailureException extends MarshallingException {
/** Constructor for <code>UnmarshallingFailureException</code>. */ /**
* Construct a <code>MarshallingFailureException</code> with the specified detail message.
* @param msg the detail message
*/
public UnmarshallingFailureException(String msg) { public UnmarshallingFailureException(String msg) {
super(msg); super(msg);
} }
/** Constructor for <code>UnmarshallingFailureException</code>. */ /**
public UnmarshallingFailureException(String msg, Throwable ex) { * Construct a <code>MarshallingFailureException</code> with the specified detail message
super(msg, ex); * and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
public UnmarshallingFailureException(String msg, Throwable cause) {
super(msg, cause);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
/** /**
@@ -23,13 +24,22 @@ package org.springframework.oxm;
*/ */
public class ValidationFailureException extends XmlMappingException { public class ValidationFailureException extends XmlMappingException {
/** Constructor for <code>ValidationFailureException</code>. */ /**
* Construct a <code>ValidationFailureException</code> with the specified detail message.
* @param msg the detail message
*/
public ValidationFailureException(String msg) { public ValidationFailureException(String msg) {
super(msg); super(msg);
} }
/** Constructor for <code>ValidationFailureException</code>. */ /**
public ValidationFailureException(String msg, Throwable ex) { * Construct a <code>ValidationFailureException</code> with the specified detail message
super(msg, ex); * and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
public ValidationFailureException(String msg, Throwable cause) {
super(msg, cause);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
import org.springframework.core.NestedRuntimeException; import org.springframework.core.NestedRuntimeException;
@@ -25,13 +26,22 @@ import org.springframework.core.NestedRuntimeException;
*/ */
public abstract class XmlMappingException extends NestedRuntimeException { public abstract class XmlMappingException extends NestedRuntimeException {
/** Constructor for <code>XmlMappingException</code>. */ /**
* Construct an <code>XmlMappingException</code> with the specified detail message.
* @param msg the detail message
*/
public XmlMappingException(String msg) { public XmlMappingException(String msg) {
super(msg); super(msg);
} }
/** Constructor for <code>XmlMappingException</code>. */ /**
public XmlMappingException(String msg, Throwable ex) { * Construct an <code>XmlMappingException</code> with the specified detail message
super(msg, ex); * and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
public XmlMappingException(String msg, Throwable cause) {
super(msg, cause);
} }
} }

View File

@@ -1,35 +1,39 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.castor;
package org.springframework.oxm.castor;
import org.exolab.castor.xml.MarshalException;
import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.MarshallingFailureException;
/**
/** * Exception thrown by {@link CastorMarshaller} whenever it encounters a mapping problem.
* Castor-specific subclass of <code>MarshallingFailureException</code>. *
* * @author Juergen Hoeller
* @author Arjen Poutsma * @since 3.0
* @see CastorUtils#convertXmlException */
* @since 3.0 public class CastorMappingException extends XmlMappingException {
*/
public class CastorMarshallingFailureException extends MarshallingFailureException { /**
* Construct a <code>CastorMappingException</code> with the specified detail message
public CastorMarshallingFailureException(MarshalException ex) { * and nested exception.
super("Castor marshalling exception: " + ex.getMessage(), ex); * @param msg the detail message
} * @param cause the nested exception
*/
} public CastorMappingException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.castor; package org.springframework.oxm.castor;
import java.io.IOException; import java.io.IOException;
@@ -21,8 +22,7 @@ import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.util.Iterator; import java.util.Map;
import java.util.Properties;
import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamReader;
@@ -30,13 +30,14 @@ import javax.xml.stream.XMLStreamWriter;
import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException; import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ResolverException; import org.exolab.castor.xml.ResolverException;
import org.exolab.castor.xml.UnmarshalHandler; import org.exolab.castor.xml.UnmarshalHandler;
import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.XMLContext; import org.exolab.castor.xml.XMLContext;
import org.exolab.castor.xml.XMLException; import org.exolab.castor.xml.XMLException;
import org.exolab.castor.xml.ValidationException;
import org.exolab.castor.xml.MarshalException;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
@@ -46,12 +47,16 @@ import org.xml.sax.ext.LexicalHandler;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.oxm.AbstractMarshaller; import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.ValidationFailureException;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.UncategorizedMappingException;
import org.springframework.oxm.support.AbstractMarshaller;
import org.springframework.oxm.support.SaxResourceUtils;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils; import org.springframework.util.xml.DomUtils;
import org.springframework.util.xml.SaxUtils;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
/** /**
@@ -76,18 +81,17 @@ import org.springframework.util.xml.StaxUtils;
public class CastorMarshaller extends AbstractMarshaller implements InitializingBean { public class CastorMarshaller extends AbstractMarshaller implements InitializingBean {
/** /**
* The default encoding used for stream access. * The default encoding used for stream access: UTF-8.
*/ */
public static final String DEFAULT_ENCODING = "UTF-8"; public static final String DEFAULT_ENCODING = "UTF-8";
private Resource[] mappingLocations; private Resource[] mappingLocations;
private String encoding = DEFAULT_ENCODING; private String encoding = DEFAULT_ENCODING;
private Class targetClass; private Class targetClass;
private XMLContext xmlContext;
private boolean validating = false; private boolean validating = false;
private boolean whitespacePreserve = false; private boolean whitespacePreserve = false;
@@ -96,93 +100,13 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
private boolean ignoreExtraElements = false; private boolean ignoreExtraElements = false;
private Properties namespaceMappings; private Map<String, String> namespaceMappings;
private XMLContext xmlContext;
/** /**
* Returns whether the Castor {@link Unmarshaller} should ignore attributes that do not match a specific field. * Set the encoding to be used for stream access.
*/
public boolean getIgnoreExtraAttributes() {
return ignoreExtraAttributes;
}
/**
* Sets whether the Castor {@link Unmarshaller} should ignore attributes that do not match a specific field. Default
* is <code>true</code>: extra attributes are ignored.
*
* @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraAttributes(boolean)
*/
public void setIgnoreExtraAttributes(boolean ignoreExtraAttributes) {
this.ignoreExtraAttributes = ignoreExtraAttributes;
}
/**
* Returns whether the Castor {@link Unmarshaller} should ignore elements that do not match a specific field.
*/
public boolean getIgnoreExtraElements() {
return ignoreExtraElements;
}
/**
* Sets whether the Castor {@link Unmarshaller} should ignore elements that do not match a specific field. Default is
* <code>false</code>, extra attributes are flagged as an error.
*
* @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraElements(boolean)
*/
public void setIgnoreExtraElements(boolean ignoreExtraElements) {
this.ignoreExtraElements = ignoreExtraElements;
}
/**
* Returns whether the Castor {@link Unmarshaller} should preserve "ignorable" whitespace.
*/
public boolean getWhitespacePreserve() {
return whitespacePreserve;
}
/**
* Sets whether the Castor {@link Unmarshaller} should preserve "ignorable" whitespace. Default is <code>false</code>.
*
* @see org.exolab.castor.xml.Unmarshaller#setWhitespacePreserve(boolean)
*/
public void setWhitespacePreserve(boolean whitespacePreserve) {
this.whitespacePreserve = whitespacePreserve;
}
/**
* Returns whether this marshaller should validate in- and outgoing documents.
*/
public boolean isValidating() {
return validating;
}
/**
* Sets whether this marshaller should validate in- and outgoing documents. Default is <code>false</code>.
*
* @see Marshaller#setValidation(boolean)
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Returns the namespace mappings. Property names are interpreted as namespace prefixes; values are namespace URIs.
*/
public Properties getNamespaceMappings() {
return namespaceMappings;
}
/**
* Sets the namespace mappings. Property names are interpreted as namespace prefixes; values are namespace URIs.
*
* @see org.exolab.castor.xml.Marshaller#setNamespaceMapping(String, String)
*/
public void setNamespaceMappings(Properties namespaceMappings) {
this.namespaceMappings = namespaceMappings;
}
/**
* Sets the encoding to be used for stream access. If this property is not set, the default encoding is used.
*
* @see #DEFAULT_ENCODING * @see #DEFAULT_ENCODING
*/ */
public void setEncoding(String encoding) { public void setEncoding(String encoding) {
@@ -190,79 +114,118 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
} }
/** /**
* Sets the locations of the Castor XML Mapping files. * Set the locations of the Castor XML Mapping files.
*/ */
public void setMappingLocation(Resource mappingLocation) { public void setMappingLocation(Resource mappingLocation) {
mappingLocations = new Resource[]{mappingLocation}; this.mappingLocations = new Resource[] {mappingLocation};
} }
/** /**
* Sets the locations of the Castor XML Mapping files. * Set the locations of the Castor XML Mapping files.
*/ */
public void setMappingLocations(Resource[] mappingLocations) { public void setMappingLocations(Resource[] mappingLocations) {
this.mappingLocations = mappingLocations; this.mappingLocations = mappingLocations;
} }
/** /**
* Sets the Castor target class. If this property is set, this <code>CastorMarshaller</code> is tied to this one * Set the Castor target class. If this property is set, this <code>CastorMarshaller</code>
* specific class. Use a mapping file for unmarshalling multiple classes. <p/> You cannot set both this property and * is tied to this one specific class. Use a mapping file for unmarshalling multiple classes.
* the mapping (location). * <p>You cannot set both this property and the mapping (location).
*/ */
public void setTargetClass(Class targetClass) { public void setTargetClass(Class targetClass) {
this.targetClass = targetClass; this.targetClass = targetClass;
} }
public final void afterPropertiesSet() throws IOException { /**
if (mappingLocations != null && targetClass != null) { * Set whether this marshaller should validate in- and outgoing documents.
* <p>Default is <code>false</code>.
* @see Marshaller#setValidation(boolean)
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Set whether the Castor {@link Unmarshaller} should preserve "ignorable" whitespace.
* <p>Default is <code>false</code>.
* @see org.exolab.castor.xml.Unmarshaller#setWhitespacePreserve(boolean)
*/
public void setWhitespacePreserve(boolean whitespacePreserve) {
this.whitespacePreserve = whitespacePreserve;
}
/**
* Set whether the Castor {@link Unmarshaller} should ignore attributes that do not match a specific field.
* <p>Default is <code>true</code>: extra attributes are ignored.
* @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraAttributes(boolean)
*/
public void setIgnoreExtraAttributes(boolean ignoreExtraAttributes) {
this.ignoreExtraAttributes = ignoreExtraAttributes;
}
/**
* Set whether the Castor {@link Unmarshaller} should ignore elements that do not match a specific field.
* <p>Default is <code>false</code>, extra attributes are flagged as an error.
* @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraElements(boolean)
*/
public void setIgnoreExtraElements(boolean ignoreExtraElements) {
this.ignoreExtraElements = ignoreExtraElements;
}
/**
* Set the namespace mappings. Property names are interpreted as namespace prefixes; values are namespace URIs.
* @see org.exolab.castor.xml.Marshaller#setNamespaceMapping(String, String)
*/
public void setNamespaceMappings(Map<String, String> namespaceMappings) {
this.namespaceMappings = namespaceMappings;
}
public final void afterPropertiesSet() throws CastorMappingException, IOException {
if (this.mappingLocations != null && this.targetClass != null) {
throw new IllegalArgumentException("Cannot set both the 'mappingLocations' and 'targetClass' property. " + throw new IllegalArgumentException("Cannot set both the 'mappingLocations' and 'targetClass' property. " +
"Set targetClass for unmarshalling a single class, and 'mappingLocations' for multiple classes'"); "Set 'targetClass' for unmarshalling a single class, and 'mappingLocations' for multiple classes.");
} }
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
if (mappingLocations != null) { if (this.mappingLocations != null) {
logger.info("Configured using " + StringUtils.arrayToCommaDelimitedString(mappingLocations)); logger.info("Configured using " + StringUtils.arrayToCommaDelimitedString(this.mappingLocations));
} }
else if (targetClass != null) { else if (this.targetClass != null) {
logger.info("Configured for target class [" + targetClass.getName() + "]"); logger.info("Configured for target class [" + this.targetClass.getName() + "]");
} }
else { else {
logger.info("Using default configuration"); logger.info("Using default configuration");
} }
} }
try { try {
xmlContext = createXMLContext(mappingLocations, targetClass); this.xmlContext = createXMLContext(this.mappingLocations, this.targetClass);
} }
catch (MappingException ex) { catch (MappingException ex) {
throw new CastorSystemException("Could not load Castor mapping: " + ex.getMessage(), ex); throw new CastorMappingException("Could not load Castor mapping", ex);
} }
catch (ResolverException rex) { catch (ResolverException ex) {
throw new CastorSystemException("Could not load Castor mapping: " + rex.getMessage(), rex); throw new CastorMappingException("Could not resolve Castor mapping", ex);
} }
} }
/** /**
* Returns <code>true</code> for all classes, i.e. Castor supports arbitrary classes. * Create the Castor <code>XMLContext</code>. Subclasses can override this to create a custom context.
*/ * <p>The default implementation loads mapping files if defined, and the target class if not defined.
public boolean supports(Class<?> clazz) {
return true;
}
/**
* Creates the Castor <code>XMLContext</code>. Subclasses can override this to create a custom context. <p/> The
* default implementation loads mapping files if defined, and the target class if not defined.
*
* @return the created resolver * @return the created resolver
* @throws MappingException when the mapping file cannot be loaded * @throws MappingException when the mapping file cannot be loaded
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @see XMLContext#addMapping(org.exolab.castor.mapping.Mapping) * @see XMLContext#addMapping(org.exolab.castor.mapping.Mapping)
* @see XMLContext#addClass(Class) * @see XMLContext#addClass(Class)
*/ */
protected XMLContext createXMLContext(Resource[] mappingLocations, Class targetClass) protected XMLContext createXMLContext(Resource[] mappingLocations, Class targetClass)
throws MappingException, IOException, ResolverException { throws MappingException, ResolverException, IOException {
XMLContext context = new XMLContext(); XMLContext context = new XMLContext();
if (!ObjectUtils.isEmpty(mappingLocations)) { if (!ObjectUtils.isEmpty(mappingLocations)) {
Mapping mapping = new Mapping(); Mapping mapping = new Mapping();
for (Resource mappingLocation : mappingLocations) { for (Resource mappingLocation : mappingLocations) {
mapping.loadMapping(SaxUtils.createInputSource(mappingLocation)); mapping.loadMapping(SaxResourceUtils.createInputSource(mappingLocation));
} }
context.addMapping(mapping); context.addMapping(mapping);
} }
@@ -272,9 +235,16 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
return context; return context;
} }
//
/**
* Returns <code>true</code> for all classes, i.e. Castor supports arbitrary classes.
*/
public boolean supports(Class<?> clazz) {
return true;
}
// Marshalling // Marshalling
//
@Override @Override
protected final void marshalDomNode(Object graph, Node node) throws XmlMappingException { protected final void marshalDomNode(Object graph, Node node) throws XmlMappingException {
@@ -323,26 +293,22 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
} }
/** /**
* Template method that allows for customizing of the given Castor {@link Marshaller}. <p/> Default implementation * Template method that allows for customizing of the given Castor {@link Marshaller}.
* invokes {@link Marshaller#setValidation(boolean)} with the property set on this marshaller, and calls {@link * <p>The default implementation invokes {@link Marshaller#setValidation(boolean)}
* Marshaller#setNamespaceMapping(String, String)} with the {@linkplain #setNamespaceMappings(java.util.Properties) * with the property set on this marshaller, and calls {@link Marshaller#setNamespaceMapping(String, String)}
* namespace mappings}. * with the {@linkplain #setNamespaceMappings(java.util.Properties) namespace mappings}.
*/ */
protected void customizeMarshaller(Marshaller marshaller) { protected void customizeMarshaller(Marshaller marshaller) {
marshaller.setValidation(isValidating()); marshaller.setValidation(this.validating);
Properties namespaceMappings = getNamespaceMappings(); if (this.namespaceMappings != null) {
if (namespaceMappings != null) { for (Map.Entry<String, String> entry : namespaceMappings.entrySet()) {
for (Iterator iterator = namespaceMappings.keySet().iterator(); iterator.hasNext();) { marshaller.setNamespaceMapping(entry.getKey(), entry.getValue());
String prefix = (String) iterator.next();
String uri = namespaceMappings.getProperty(prefix);
marshaller.setNamespaceMapping(prefix, uri);
} }
} }
} }
//
// Unmarshalling // Unmarshalling
//
@Override @Override
protected final Object unmarshalDomNode(Node node) throws XmlMappingException { protected final Object unmarshalDomNode(Node node) throws XmlMappingException {
@@ -381,13 +347,14 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
return unmarshalSaxReader(reader, new InputSource()); return unmarshalSaxReader(reader, new InputSource());
} }
catch (IOException ex) { catch (IOException ex) {
throw new CastorUnmarshallingFailureException(new MarshalException(ex)); throw new UnmarshallingFailureException("Failed to read XML stream", ex);
} }
} }
@Override @Override
protected final Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) protected final Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
throws XmlMappingException, IOException { throws XmlMappingException, IOException {
UnmarshalHandler unmarshalHandler = createUnmarshaller().createHandler(); UnmarshalHandler unmarshalHandler = createUnmarshaller().createHandler();
try { try {
ContentHandler contentHandler = Unmarshaller.getContentHandler(unmarshalHandler); ContentHandler contentHandler = Unmarshaller.getContentHandler(unmarshalHandler);
@@ -396,7 +363,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
return unmarshalHandler.getObject(); return unmarshalHandler.getObject();
} }
catch (SAXException ex) { catch (SAXException ex) {
throw new CastorUnmarshallingFailureException(ex); throw new UnmarshallingFailureException("SAX reader exception", ex);
} }
} }
@@ -407,47 +374,60 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
return unmarshalSaxReader(reader, new InputSource()); return unmarshalSaxReader(reader, new InputSource());
} }
catch (IOException ex) { catch (IOException ex) {
throw new CastorUnmarshallingFailureException(new MarshalException(ex)); throw new UnmarshallingFailureException("Failed to read XML stream", ex);
} }
} }
private Unmarshaller createUnmarshaller() { private Unmarshaller createUnmarshaller() {
Unmarshaller unmarshaller = xmlContext.createUnmarshaller(); Unmarshaller unmarshaller = this.xmlContext.createUnmarshaller();
if (targetClass != null) { if (this.targetClass != null) {
unmarshaller.setClass(targetClass); unmarshaller.setClass(this.targetClass);
unmarshaller.setClassLoader(targetClass.getClassLoader()); unmarshaller.setClassLoader(this.targetClass.getClassLoader());
} }
customizeUnmarshaller(unmarshaller); customizeUnmarshaller(unmarshaller);
return unmarshaller; return unmarshaller;
} }
/** /**
* Template method that allows for customizing of the given Castor {@link Unmarshaller}. <p/> Default implementation * Template method that allows for customizing of the given Castor {@link Unmarshaller}.
* invokes {@link Unmarshaller#setValidation(boolean)}, {@link Unmarshaller#setWhitespacePreserve(boolean)}, {@link * <p>The default implementation invokes {@link Unmarshaller#setValidation(boolean)},
* Unmarshaller#setIgnoreExtraAttributes(boolean)}, and {@link Unmarshaller#setIgnoreExtraElements(boolean)} with the * {@link Unmarshaller#setWhitespacePreserve(boolean)}, {@link Unmarshaller#setIgnoreExtraAttributes(boolean)},
* properties set on this marshaller. * and {@link Unmarshaller#setIgnoreExtraElements(boolean)} with the properties set on this marshaller.
*/ */
protected void customizeUnmarshaller(Unmarshaller unmarshaller) { protected void customizeUnmarshaller(Unmarshaller unmarshaller) {
unmarshaller.setValidation(isValidating()); unmarshaller.setValidation(this.validating);
unmarshaller.setWhitespacePreserve(getWhitespacePreserve()); unmarshaller.setWhitespacePreserve(this.whitespacePreserve);
unmarshaller.setIgnoreExtraAttributes(getIgnoreExtraAttributes()); unmarshaller.setIgnoreExtraAttributes(this.ignoreExtraAttributes);
unmarshaller.setIgnoreExtraElements(getIgnoreExtraElements()); unmarshaller.setIgnoreExtraElements(this.ignoreExtraElements);
} }
/** /**
* Converts the given <code>CastorException</code> to an appropriate exception from the * Convert the given <code>XMLException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy. <p/> The default implementation delegates to * <code>org.springframework.oxm</code> hierarchy.
* <code>CastorUtils</code>. Can be overridden in subclasses. <p/> A boolean flag is used to indicate whether this * <p>A boolean flag is used to indicate whether this exception occurs during marshalling or
* exception occurs during marshalling or unmarshalling, since Castor itself does not make this distinction in its * unmarshalling, since Castor itself does not make this distinction in its exception hierarchy.
* exception hierarchy. * @param ex Castor <code>XMLException</code> that occured
* * @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>),
* @param ex Castor <code>XMLException</code> that occured * or unmarshalling (<code>false</code>)
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code> * @return the corresponding <code>XmlMappingException</code>
* @see CastorUtils#convertXmlException * @see CastorUtils#convertCastorException
*/ */
public XmlMappingException convertCastorException(XMLException ex, boolean marshalling) { protected XmlMappingException convertCastorException(XMLException ex, boolean marshalling) {
return CastorUtils.convertXmlException(ex, marshalling); if (ex instanceof ValidationException) {
return new ValidationFailureException("Castor validation exception", ex);
}
else if (ex instanceof MarshalException) {
if (marshalling) {
return new MarshallingFailureException("Castor marshalling exception", ex);
}
else {
return new UnmarshallingFailureException("Castor unmarshalling exception", ex);
}
}
else {
// fallback
return new UncategorizedMappingException("Unknown Castor exception", ex);
}
} }
} }

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.castor;
import org.exolab.castor.xml.MarshalException;
import org.xml.sax.SAXException;
import org.springframework.oxm.UnmarshallingFailureException;
/**
* Castor-specific subclass of <code>UnmarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see CastorUtils#convertXmlException
* @since 3.0
*/
public class CastorUnmarshallingFailureException extends UnmarshallingFailureException {
public CastorUnmarshallingFailureException(MarshalException ex) {
super("Castor unmarshalling exception: " + ex.getMessage(), ex);
}
public CastorUnmarshallingFailureException(SAXException ex) {
super("Castor unmarshalling exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,60 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.castor;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import org.exolab.castor.xml.XMLException;
import org.springframework.oxm.XmlMappingException;
/**
* Generic utility methods for working with Castor. Mainly for internal use within the framework.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class CastorUtils {
/**
* Converts the given <code>XMLException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy. <p/> A boolean flag is used to indicate whether this exception
* occurs during marshalling or unmarshalling, since Castor itself does not make this distinction in its exception
* hierarchy.
*
* @param ex Castor <code>XMLException</code> that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
*/
public static XmlMappingException convertXmlException(XMLException ex, boolean marshalling) {
if (ex instanceof MarshalException) {
MarshalException marshalException = (MarshalException) ex;
if (marshalling) {
return new CastorMarshallingFailureException(marshalException);
}
else {
return new CastorUnmarshallingFailureException(marshalException);
}
}
else if (ex instanceof ValidationException) {
return new CastorValidationFailureException((ValidationException) ex);
}
// fallback
return new CastorSystemException("Unknown Castor exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.castor;
import org.exolab.castor.xml.ValidationException;
import org.springframework.oxm.ValidationFailureException;
/**
* Castor-specific subclass of <code>MarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see CastorUtils#convertXmlException
* @since 3.0
*/
public class CastorValidationFailureException extends ValidationFailureException {
public CastorValidationFailureException(ValidationException ex) {
super("Castor validation exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,6 +1,6 @@
/* /*
* Copyright 2007 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2008 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@@ -1,6 +1,6 @@
/* /*
* Copyright 2008 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@@ -32,4 +32,5 @@ public class OxmNamespaceHandler extends NamespaceHandlerSupport {
registerBeanDefinitionParser("jibx-marshaller", new JibxMarshallerBeanDefinitionParser()); registerBeanDefinitionParser("jibx-marshaller", new JibxMarshallerBeanDefinitionParser());
registerBeanDefinitionParser("xmlbeans-marshaller", new XmlBeansMarshallerBeanDefinitionParser()); registerBeanDefinitionParser("xmlbeans-marshaller", new XmlBeansMarshallerBeanDefinitionParser());
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2008 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,4 +45,5 @@ class XmlBeansMarshallerBeanDefinitionParser extends AbstractSingleBeanDefinitio
beanDefinitionBuilder.addPropertyReference("xmlOptions", optionsName); beanDefinitionBuilder.addPropertyReference("xmlOptions", optionsName);
} }
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -34,9 +34,12 @@ import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Marshaller; import javax.xml.bind.Marshaller;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEventHandler; import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.ValidationException;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentMarshaller;
@@ -61,16 +64,20 @@ import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.UncategorizedMappingException;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.ValidationFailureException;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.mime.MimeContainer; import org.springframework.oxm.mime.MimeContainer;
import org.springframework.oxm.mime.MimeMarshaller; import org.springframework.oxm.mime.MimeMarshaller;
import org.springframework.oxm.mime.MimeUnmarshaller; import org.springframework.oxm.mime.MimeUnmarshaller;
import org.springframework.oxm.support.SaxResourceUtils;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.util.xml.SaxUtils;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
/** /**
@@ -97,55 +104,45 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
private static final String CID = "cid:"; private static final String CID = "cid:";
/** /**
* Logger available to subclasses. * Logger available to subclasses.
*/ */
private static final Log logger = LogFactory.getLog(Jaxb2Marshaller.class); protected final Log logger = LogFactory.getLog(getClass());
private String contextPath; private String contextPath;
private Map<String, Object> marshallerProperties;
private Map<String, Object> unmarshallerProperties;
private JAXBContext jaxbContext;
private ValidationEventHandler validationEventHandler;
private ClassLoader classLoader;
private Resource[] schemaResources;
private String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
private Marshaller.Listener marshallerListener;
private Unmarshaller.Listener unmarshallerListener;
private XmlAdapter[] adapters;
private Schema schema;
private Class[] classesToBeBound; private Class[] classesToBeBound;
private Map<String, ?> jaxbContextProperties; private Map<String, ?> jaxbContextProperties;
private Map<String, Object> marshallerProperties;
private Map<String, Object> unmarshallerProperties;
private Marshaller.Listener marshallerListener;
private Unmarshaller.Listener unmarshallerListener;
private ValidationEventHandler validationEventHandler;
private XmlAdapter[] adapters;
private Resource[] schemaResources;
private String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
private boolean mtomEnabled = false; private boolean mtomEnabled = false;
public void setBeanClassLoader(ClassLoader classLoader) { private ClassLoader beanClassLoader;
this.classLoader = classLoader;
} private JAXBContext jaxbContext;
private Schema schema;
/** /**
* Sets the <code>XmlAdapter</code>s to be registered with the JAXB <code>Marshaller</code> and * Set a JAXB context path.
* <code>Unmarshaller</code>
*/
public void setAdapters(XmlAdapter[] adapters) {
this.adapters = adapters;
}
/**
* Sets the JAXB Context path.
*/ */
public void setContextPath(String contextPath) { public void setContextPath(String contextPath) {
Assert.hasText(contextPath, "'contextPath' must not be null"); Assert.hasText(contextPath, "'contextPath' must not be null");
@@ -153,8 +150,8 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
/** /**
* Sets multiple JAXB Context paths. The given array of context paths is converted to a colon-delimited string, as * Set multiple JAXB context paths. The given array of context paths is converted to a
* supported by JAXB. * colon-delimited string, as supported by JAXB.
*/ */
public void setContextPaths(String[] contextPaths) { public void setContextPaths(String[] contextPaths) {
Assert.notEmpty(contextPaths, "'contextPaths' must not be empty"); Assert.notEmpty(contextPaths, "'contextPaths' must not be empty");
@@ -162,73 +159,24 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
/** /**
* Sets the list of java classes to be recognized by a newly created JAXBContext. Setting this property or * Set the list of Java classes to be recognized by a newly created JAXBContext.
* <code>contextPath</code> is required. * Setting this property or {@link #setContextPath "contextPath"} is required.
*
* @see #setContextPath(String)
*/ */
public void setClassesToBeBound(Class[] classesToBeBound) { public void setClassesToBeBound(Class[] classesToBeBound) {
this.classesToBeBound = classesToBeBound; this.classesToBeBound = classesToBeBound;
} }
/** /**
* Sets the <code>JAXBContext</code> properties. These implementation-specific properties will be set on the * Set the <code>JAXBContext</code> properties. These implementation-specific
* <code>JAXBContext</code>. * properties will be set on the underlying <code>JAXBContext</code>.
*/ */
public void setJaxbContextProperties(Map<String, ?> jaxbContextProperties) { public void setJaxbContextProperties(Map<String, ?> jaxbContextProperties) {
this.jaxbContextProperties = jaxbContextProperties; this.jaxbContextProperties = jaxbContextProperties;
} }
/** /**
* Sets the <code>Marshaller.Listener</code> to be registered with the JAXB <code>Marshaller</code>. * Set the JAXB <code>Marshaller</code> properties. These properties will be set on the
*/ * underlying JAXB <code>Marshaller</code>, and allow for features such as indentation.
public void setMarshallerListener(Marshaller.Listener marshallerListener) {
this.marshallerListener = marshallerListener;
}
/**
* Indicates whether MTOM support should be enabled or not. Default is <code>false</code>, marshalling using XOP/MTOM
* is not enabled.
*/
public void setMtomEnabled(boolean mtomEnabled) {
this.mtomEnabled = mtomEnabled;
}
/**
* Sets the schema language. Default is the W3C XML Schema: <code>http://www.w3.org/2001/XMLSchema"</code>.
*
* @see XMLConstants#W3C_XML_SCHEMA_NS_URI
* @see XMLConstants#RELAXNG_NS_URI
*/
public void setSchemaLanguage(String schemaLanguage) {
this.schemaLanguage = schemaLanguage;
}
/**
* Sets the schema resource to use for validation.
*/
public void setSchema(Resource schemaResource) {
schemaResources = new Resource[]{schemaResource};
}
/**
* Sets the schema resources to use for validation.
*/
public void setSchemas(Resource[] schemaResources) {
this.schemaResources = schemaResources;
}
/**
* Sets the <code>Unmarshaller.Listener</code> to be registered with the JAXB <code>Unmarshaller</code>.
*/
public void setUnmarshallerListener(Unmarshaller.Listener unmarshallerListener) {
this.unmarshallerListener = unmarshallerListener;
}
/**
* Sets the JAXB <code>Marshaller</code> properties. These properties will be set on the underlying JAXB
* <code>Marshaller</code>, and allow for features such as indentation.
*
* @param properties the properties * @param properties the properties
* @see Marshaller#setProperty(String,Object) * @see Marshaller#setProperty(String,Object)
* @see Marshaller#JAXB_ENCODING * @see Marshaller#JAXB_ENCODING
@@ -241,9 +189,8 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
/** /**
* Sets the JAXB <code>Unmarshaller</code> properties. These properties will be set on the underlying JAXB * Set the JAXB <code>Unmarshaller</code> properties. These properties will be set on the
* <code>Unmarshaller</code>. * underlying JAXB <code>Unmarshaller</code>.
*
* @param properties the properties * @param properties the properties
* @see javax.xml.bind.Unmarshaller#setProperty(String,Object) * @see javax.xml.bind.Unmarshaller#setProperty(String,Object)
*/ */
@@ -252,43 +199,86 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
/** /**
* Sets the JAXB validation event handler. This event handler will be called by JAXB if any validation errors are * Specify the <code>Marshaller.Listener</code> to be registered with the JAXB <code>Marshaller</code>.
* encountered during calls to any of the marshal API's. */
* public void setMarshallerListener(Marshaller.Listener marshallerListener) {
* @param validationEventHandler the event handler this.marshallerListener = marshallerListener;
}
/**
* Set the <code>Unmarshaller.Listener</code> to be registered with the JAXB <code>Unmarshaller</code>.
*/
public void setUnmarshallerListener(Unmarshaller.Listener unmarshallerListener) {
this.unmarshallerListener = unmarshallerListener;
}
/**
* Set the JAXB validation event handler. This event handler will be called by JAXB
* if any validation errors are encountered during calls to any of the marshal APIs.
*/ */
public void setValidationEventHandler(ValidationEventHandler validationEventHandler) { public void setValidationEventHandler(ValidationEventHandler validationEventHandler) {
this.validationEventHandler = validationEventHandler; this.validationEventHandler = validationEventHandler;
} }
/**
* Specify the <code>XmlAdapter</code>s to be registered with the JAXB <code>Marshaller</code>
* and <code>Unmarshaller</code>
*/
public void setAdapters(XmlAdapter[] adapters) {
this.adapters = adapters;
}
/**
* Set the schema resource to use for validation.
*/
public void setSchema(Resource schemaResource) {
this.schemaResources = new Resource[] {schemaResource};
}
/**
* Set the schema resources to use for validation.
*/
public void setSchemas(Resource[] schemaResources) {
this.schemaResources = schemaResources;
}
/**
* Set the schema language. Default is the W3C XML Schema: <code>http://www.w3.org/2001/XMLSchema"</code>.
* @see XMLConstants#W3C_XML_SCHEMA_NS_URI
* @see XMLConstants#RELAXNG_NS_URI
*/
public void setSchemaLanguage(String schemaLanguage) {
this.schemaLanguage = schemaLanguage;
}
/**
* Specify whether MTOM support should be enabled or not.
* Default is <code>false</code>: marshalling using XOP/MTOM not being enabled.
*/
public void setMtomEnabled(boolean mtomEnabled) {
this.mtomEnabled = mtomEnabled;
}
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
public final void afterPropertiesSet() throws Exception { public final void afterPropertiesSet() throws Exception {
if (StringUtils.hasLength(contextPath) && !ObjectUtils.isEmpty(classesToBeBound)) { this.jaxbContext = createJaxbContext();
throw new IllegalArgumentException("specify either contextPath or classesToBeBound property; not both"); if (!ObjectUtils.isEmpty(this.schemaResources)) {
} this.schema = loadSchema(this.schemaResources, this.schemaLanguage);
try {
jaxbContext = createJaxbContext();
}
catch (JAXBException ex) {
throw convertJaxbException(ex);
} }
} }
/*
* JAXBContext
*/
protected JAXBContext createJaxbContext() throws Exception { protected JAXBContext createJaxbContext() throws Exception {
if (!ObjectUtils.isEmpty(schemaResources)) { if (StringUtils.hasLength(this.contextPath) && !ObjectUtils.isEmpty(this.classesToBeBound)) {
if (logger.isDebugEnabled()) { throw new IllegalArgumentException("Specify either 'contextPath' or 'classesToBeBound property'; not both");
logger.debug(
"Setting validation schema to " + StringUtils.arrayToCommaDelimitedString(schemaResources));
}
schema = loadSchema(schemaResources, schemaLanguage);
} }
if (StringUtils.hasLength(contextPath)) { if (StringUtils.hasLength(this.contextPath)) {
return createJaxbContextFromContextPath(); return createJaxbContextFromContextPath();
} }
else if (!ObjectUtils.isEmpty(classesToBeBound)) { else if (!ObjectUtils.isEmpty(this.classesToBeBound)) {
return createJaxbContextFromClasses(); return createJaxbContextFromClasses();
} }
else { else {
@@ -298,22 +288,22 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
private JAXBContext createJaxbContextFromContextPath() throws JAXBException { private JAXBContext createJaxbContextFromContextPath() throws JAXBException {
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
logger.info("Creating JAXBContext with context path [" + contextPath + "]"); logger.info("Creating JAXBContext with context path [" + this.contextPath + "]");
} }
if (jaxbContextProperties != null) { if (this.jaxbContextProperties != null) {
if (classLoader != null) { if (this.beanClassLoader != null) {
return JAXBContext.newInstance(contextPath, classLoader, jaxbContextProperties); return JAXBContext.newInstance(this.contextPath, this.beanClassLoader, this.jaxbContextProperties);
} }
else { else {
return JAXBContext.newInstance(contextPath, ClassUtils.getDefaultClassLoader(), jaxbContextProperties); return JAXBContext.newInstance(this.contextPath, ClassUtils.getDefaultClassLoader(), this.jaxbContextProperties);
} }
} }
else { else {
if (classLoader != null) { if (this.beanClassLoader != null) {
return JAXBContext.newInstance(contextPath, classLoader); return JAXBContext.newInstance(this.contextPath, this.beanClassLoader);
} }
else { else {
return JAXBContext.newInstance(contextPath); return JAXBContext.newInstance(this.contextPath);
} }
} }
} }
@@ -321,17 +311,20 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
private JAXBContext createJaxbContextFromClasses() throws JAXBException { private JAXBContext createJaxbContextFromClasses() throws JAXBException {
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
logger.info("Creating JAXBContext with classes to be bound [" + logger.info("Creating JAXBContext with classes to be bound [" +
StringUtils.arrayToCommaDelimitedString(classesToBeBound) + "]"); StringUtils.arrayToCommaDelimitedString(this.classesToBeBound) + "]");
} }
if (jaxbContextProperties != null) { if (this.jaxbContextProperties != null) {
return JAXBContext.newInstance(classesToBeBound, jaxbContextProperties); return JAXBContext.newInstance(this.classesToBeBound, this.jaxbContextProperties);
} }
else { else {
return JAXBContext.newInstance(classesToBeBound); return JAXBContext.newInstance(this.classesToBeBound);
} }
} }
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException { private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
if (logger.isDebugEnabled()) {
logger.debug("Setting validation schema to " + StringUtils.arrayToCommaDelimitedString(this.schemaResources));
}
Assert.notEmpty(resources, "No resources given"); Assert.notEmpty(resources, "No resources given");
Assert.hasLength(schemaLanguage, "No schema language provided"); Assert.hasLength(schemaLanguage, "No schema language provided");
Source[] schemaSources = new Source[resources.length]; Source[] schemaSources = new Source[resources.length];
@@ -340,13 +333,14 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
for (int i = 0; i < resources.length; i++) { for (int i = 0; i < resources.length; i++) {
Assert.notNull(resources[i], "Resource is null"); Assert.notNull(resources[i], "Resource is null");
Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist"); Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
InputSource inputSource = SaxUtils.createInputSource(resources[i]); InputSource inputSource = SaxResourceUtils.createInputSource(resources[i]);
schemaSources[i] = new SAXSource(xmlReader, inputSource); schemaSources[i] = new SAXSource(xmlReader, inputSource);
} }
SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
return schemaFactory.newSchema(schemaSources); return schemaFactory.newSchema(schemaSources);
} }
public boolean supports(Class<?> clazz) { public boolean supports(Class<?> clazz) {
if (JAXBElement.class.isAssignableFrom(clazz)) { if (JAXBElement.class.isAssignableFrom(clazz)) {
return true; return true;
@@ -354,9 +348,9 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
else if (clazz.getAnnotation(XmlRootElement.class) != null) { else if (clazz.getAnnotation(XmlRootElement.class) != null) {
return true; return true;
} }
if (StringUtils.hasLength(contextPath)) { if (StringUtils.hasLength(this.contextPath)) {
String packageName = ClassUtils.getPackageName(clazz); String packageName = ClassUtils.getPackageName(clazz);
String[] contextPaths = StringUtils.tokenizeToStringArray(contextPath, ":"); String[] contextPaths = StringUtils.tokenizeToStringArray(this.contextPath, ":");
for (String contextPath : contextPaths) { for (String contextPath : contextPaths) {
if (contextPath.equals(packageName)) { if (contextPath.equals(packageName)) {
return true; return true;
@@ -364,60 +358,14 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
return false; return false;
} }
else if (!ObjectUtils.isEmpty(classesToBeBound)) { else if (!ObjectUtils.isEmpty(this.classesToBeBound)) {
return Arrays.asList(classesToBeBound).contains(clazz); return Arrays.asList(this.classesToBeBound).contains(clazz);
} }
return false; return false;
} }
/*
* Marshalling
*/
/** // Marshalling
* Returns a newly created JAXB marshaller. JAXB marshallers are not necessarily thread safe.
*/
private Marshaller createMarshaller() {
try {
Marshaller marshaller = jaxbContext.createMarshaller();
initJaxbMarshaller(marshaller);
return marshaller;
}
catch (JAXBException ex) {
throw convertJaxbException(ex);
}
}
/**
* Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior. Gets called
* after creation of JAXB <code>Marshaller</code>, and after the respective properties have been set.
*
* <p>Default implementation sets the {@link #setMarshallerProperties(Map) defined properties}, the {@link
* #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
* schemas}, {@link #setMarshallerListener(Marshaller.Listener) listener}, and {@link #setAdapters(XmlAdapter[])
* adapters}.
*/
protected void initJaxbMarshaller(Marshaller marshaller) throws JAXBException {
if (marshallerProperties != null) {
for (String name : marshallerProperties.keySet()) {
marshaller.setProperty(name, marshallerProperties.get(name));
}
}
if (validationEventHandler != null) {
marshaller.setEventHandler(validationEventHandler);
}
if (schema != null) {
marshaller.setSchema(schema);
}
if (marshallerListener != null) {
marshaller.setListener(marshallerListener);
}
if (adapters != null) {
for (XmlAdapter adapter : adapters) {
marshaller.setAdapter(adapter);
}
}
}
public void marshal(Object graph, Result result) throws XmlMappingException { public void marshal(Object graph, Result result) throws XmlMappingException {
marshal(graph, result, null); marshal(graph, result, null);
@@ -426,7 +374,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
public void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException { public void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException {
try { try {
Marshaller marshaller = createMarshaller(); Marshaller marshaller = createMarshaller();
if (mtomEnabled && mimeContainer != null) { if (this.mtomEnabled && mimeContainer != null) {
marshaller.setAttachmentMarshaller(new Jaxb2AttachmentMarshaller(mimeContainer)); marshaller.setAttachmentMarshaller(new Jaxb2AttachmentMarshaller(mimeContainer));
} }
if (StaxUtils.isStaxResult(result)) { if (StaxUtils.isStaxResult(result)) {
@@ -457,18 +405,14 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
} }
/*
* Unmarshalling
*/
/** /**
* Returns a newly created JAXB unmarshaller. JAXB unmarshallers are not necessarily thread safe. * Return a newly created JAXB marshaller. JAXB marshallers are not necessarily thread safe.
*/ */
private Unmarshaller createUnmarshaller() { protected Marshaller createMarshaller() {
try { try {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Marshaller marshaller = this.jaxbContext.createMarshaller();
initJaxbUnmarshaller(unmarshaller); initJaxbMarshaller(marshaller);
return unmarshaller; return marshaller;
} }
catch (JAXBException ex) { catch (JAXBException ex) {
throw convertJaxbException(ex); throw convertJaxbException(ex);
@@ -476,36 +420,38 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
/** /**
* Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior. Gets called * Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
* after creation of JAXB <code>Marshaller</code>, and after the respective properties have been set. * Gets called after creation of JAXB <code>Marshaller</code>, and after the respective properties have been set.
* * <p>The default implementation sets the {@link #setMarshallerProperties(Map) defined properties}, the {@link
* <p>Default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link
* #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[]) * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
* schemas}, {@link #setUnmarshallerListener(Unmarshaller.Listener) listener}, and {@link #setAdapters(XmlAdapter[]) * schemas}, {@link #setMarshallerListener(Marshaller.Listener) listener}, and {@link #setAdapters(XmlAdapter[])
* adapters}. * adapters}.
*/ */
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException { protected void initJaxbMarshaller(Marshaller marshaller) throws JAXBException {
if (unmarshallerProperties != null) { if (this.marshallerProperties != null) {
for (String name : unmarshallerProperties.keySet()) { for (String name : this.marshallerProperties.keySet()) {
unmarshaller.setProperty(name, unmarshallerProperties.get(name)); marshaller.setProperty(name, this.marshallerProperties.get(name));
} }
} }
if (validationEventHandler != null) { if (this.marshallerListener != null) {
unmarshaller.setEventHandler(validationEventHandler); marshaller.setListener(this.marshallerListener);
} }
if (schema != null) { if (this.validationEventHandler != null) {
unmarshaller.setSchema(schema); marshaller.setEventHandler(this.validationEventHandler);
} }
if (unmarshallerListener != null) { if (this.adapters != null) {
unmarshaller.setListener(unmarshallerListener); for (XmlAdapter adapter : this.adapters) {
} marshaller.setAdapter(adapter);
if (adapters != null) {
for (XmlAdapter adapter : adapters) {
unmarshaller.setAdapter(adapter);
} }
} }
if (this.schema != null) {
marshaller.setSchema(this.schema);
}
} }
// Unmarshalling
public Object unmarshal(Source source) throws XmlMappingException { public Object unmarshal(Source source) throws XmlMappingException {
return unmarshal(source, null); return unmarshal(source, null);
} }
@@ -513,7 +459,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
public Object unmarshal(Source source, MimeContainer mimeContainer) throws XmlMappingException { public Object unmarshal(Source source, MimeContainer mimeContainer) throws XmlMappingException {
try { try {
Unmarshaller unmarshaller = createUnmarshaller(); Unmarshaller unmarshaller = createUnmarshaller();
if (mtomEnabled && mimeContainer != null) { if (this.mtomEnabled && mimeContainer != null) {
unmarshaller.setAttachmentUnmarshaller(new Jaxb2AttachmentUnmarshaller(mimeContainer)); unmarshaller.setAttachmentUnmarshaller(new Jaxb2AttachmentUnmarshaller(mimeContainer));
} }
if (StaxUtils.isStaxSource(source)) { if (StaxUtils.isStaxSource(source)) {
@@ -545,21 +491,72 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
/** /**
* Convert the given <code>JAXBException</code> to an appropriate exception from the * Return a newly created JAXB unmarshaller. JAXB unmarshallers are not necessarily thread safe.
* <code>org.springframework.oxm</code> hierarchy. <p/> The default implementation delegates to <code>JaxbUtils</code>.
* Can be overridden in subclasses.
*
* @param ex <code>JAXBException</code> that occured
* @return the corresponding <code>XmlMappingException</code> instance
* @see org.springframework.oxm.jaxb.JaxbUtils#convertJaxbException
*/ */
protected XmlMappingException convertJaxbException(JAXBException ex) { protected Unmarshaller createUnmarshaller() {
return JaxbUtils.convertJaxbException(ex); try {
Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller();
initJaxbUnmarshaller(unmarshaller);
return unmarshaller;
}
catch (JAXBException ex) {
throw convertJaxbException(ex);
}
}
/**
* Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
* Gets called after creation of JAXB <code>Marshaller</code>, and after the respective properties have been set.
* <p>The default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link
* #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
* schemas}, {@link #setUnmarshallerListener(Unmarshaller.Listener) listener}, and {@link #setAdapters(XmlAdapter[])
* adapters}.
*/
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
if (this.unmarshallerProperties != null) {
for (String name : this.unmarshallerProperties.keySet()) {
unmarshaller.setProperty(name, this.unmarshallerProperties.get(name));
}
}
if (this.unmarshallerListener != null) {
unmarshaller.setListener(this.unmarshallerListener);
}
if (this.validationEventHandler != null) {
unmarshaller.setEventHandler(this.validationEventHandler);
}
if (this.adapters != null) {
for (XmlAdapter adapter : this.adapters) {
unmarshaller.setAdapter(adapter);
}
}
if (this.schema != null) {
unmarshaller.setSchema(this.schema);
}
}
/**
* Convert the given <code>JAXBException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy.
* @param ex <code>JAXBException</code> that occured
* @return the corresponding <code>XmlMappingException</code>
*/
protected XmlMappingException convertJaxbException(JAXBException ex) {
if (ex instanceof ValidationException) {
return new ValidationFailureException("JAXB validation exception", ex);
}
else if (ex instanceof MarshalException) {
return new MarshallingFailureException("JAXB marshalling exception", ex);
}
else if (ex instanceof UnmarshalException) {
return new UnmarshallingFailureException("JAXB unmarshalling exception", ex);
}
else {
// fallback
return new UncategorizedMappingException("Unknown JAXB exception", ex);
}
} }
/*
* Inner classes
*/
private static class Jaxb2AttachmentMarshaller extends AttachmentMarshaller { private static class Jaxb2AttachmentMarshaller extends AttachmentMarshaller {
@@ -570,12 +567,8 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
@Override @Override
public String addMtomAttachment(byte[] data, public String addMtomAttachment(byte[] data, int offset, int length, String mimeType,
int offset, String elementNamespace, String elementLocalName) {
int length,
String mimeType,
String elementNamespace,
String elementLocalName) {
ByteArrayDataSource dataSource = new ByteArrayDataSource(mimeType, data, offset, length); ByteArrayDataSource dataSource = new ByteArrayDataSource(mimeType, data, offset, length);
return addMtomAttachment(new DataHandler(dataSource), elementNamespace, elementLocalName); return addMtomAttachment(new DataHandler(dataSource), elementNamespace, elementLocalName);
} }
@@ -584,7 +577,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
public String addMtomAttachment(DataHandler dataHandler, String elementNamespace, String elementLocalName) { public String addMtomAttachment(DataHandler dataHandler, String elementNamespace, String elementLocalName) {
String host = getHost(elementNamespace, dataHandler); String host = getHost(elementNamespace, dataHandler);
String contentId = UUID.randomUUID() + "@" + host; String contentId = UUID.randomUUID() + "@" + host;
mimeContainer.addAttachment("<" + contentId + ">", dataHandler); this.mimeContainer.addAttachment("<" + contentId + ">", dataHandler);
try { try {
contentId = URLEncoder.encode(contentId, "UTF-8"); contentId = URLEncoder.encode(contentId, "UTF-8");
} }
@@ -614,10 +607,11 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
@Override @Override
public boolean isXOPPackage() { public boolean isXOPPackage() {
return mimeContainer.convertToXopPackage(); return this.mimeContainer.convertToXopPackage();
} }
} }
private static class Jaxb2AttachmentUnmarshaller extends AttachmentUnmarshaller { private static class Jaxb2AttachmentUnmarshaller extends AttachmentUnmarshaller {
private final MimeContainer mimeContainer; private final MimeContainer mimeContainer;
@@ -633,7 +627,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); return FileCopyUtils.copyToByteArray(dataHandler.getInputStream());
} }
catch (IOException ex) { catch (IOException ex) {
throw new JaxbUnmarshallingFailureException(ex); throw new UnmarshallingFailureException("Couldn't read attachment", ex);
} }
} }
@@ -649,15 +643,16 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
contentId = '<' + contentId + '>'; contentId = '<' + contentId + '>';
} }
return mimeContainer.getAttachment(contentId); return this.mimeContainer.getAttachment(contentId);
} }
@Override @Override
public boolean isXOPPackage() { public boolean isXOPPackage() {
return mimeContainer.isXopPackage(); return this.mimeContainer.isXopPackage();
} }
} }
/** /**
* DataSource that wraps around a byte array. * DataSource that wraps around a byte array.
*/ */
@@ -679,7 +674,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
public InputStream getInputStream() throws IOException { public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data, offset, length); return new ByteArrayInputStream(this.data, this.offset, this.length);
} }
public OutputStream getOutputStream() throws IOException { public OutputStream getOutputStream() throws IOException {
@@ -687,7 +682,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, BeanCl
} }
public String getContentType() { public String getContentType() {
return contentType; return this.contentType;
} }
public String getName() { public String getName() {

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jaxb;
import javax.xml.bind.MarshalException;
import org.springframework.oxm.MarshallingFailureException;
/**
* JAXB-specific subclass of <code>MarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see JaxbUtils#convertJaxbException
* @since 3.0
*/
public class JaxbMarshallingFailureException extends MarshallingFailureException {
public JaxbMarshallingFailureException(MarshalException ex) {
super("JAXB marshalling exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jaxb;
import javax.xml.bind.JAXBException;
import org.springframework.oxm.UncategorizedXmlMappingException;
/**
* JAXB-specific subclass of <code>UncategorizedXmlMappingException</code>, for <code>JAXBException</code>s that cannot
* be distinguished further.
*
* @author Arjen Poutsma
* @see JaxbUtils#convertJaxbException(javax.xml.bind.JAXBException)
* @since 3.0
*/
public class JaxbSystemException extends UncategorizedXmlMappingException {
public JaxbSystemException(JAXBException ex) {
super(ex.getMessage(), ex);
}
}

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jaxb;
import java.io.IOException;
import javax.xml.bind.UnmarshalException;
import org.springframework.oxm.UnmarshallingFailureException;
/**
* JAXB-specific subclass of <code>UnmarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class JaxbUnmarshallingFailureException extends UnmarshallingFailureException {
public JaxbUnmarshallingFailureException(UnmarshalException ex) {
super("JAXB unmarshalling exception: " + ex.getMessage(), ex);
}
public JaxbUnmarshallingFailureException(IOException ex) {
super("JAXB unmarshalling exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,54 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jaxb;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.ValidationException;
import org.springframework.oxm.XmlMappingException;
/**
* Generic utility methods for working with JAXB. Mainly for internal use within the framework.
*
* @author Arjen Poutsma
* @since 3.0
*/
public abstract class JaxbUtils {
/**
* Converts the given <code>JAXBException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy.
*
* @param ex <code>JAXBException</code> that occured
* @return the corresponding <code>XmlMappingException</code>
*/
public static XmlMappingException convertJaxbException(JAXBException ex) {
if (ex instanceof MarshalException) {
return new JaxbMarshallingFailureException((MarshalException) ex);
}
else if (ex instanceof UnmarshalException) {
return new JaxbUnmarshallingFailureException((UnmarshalException) ex);
}
else if (ex instanceof ValidationException) {
return new JaxbValidationFailureException((ValidationException) ex);
}
// fallback
return new JaxbSystemException(ex);
}
}

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jaxb;
import javax.xml.bind.ValidationException;
import org.springframework.oxm.ValidationFailureException;
/**
* JAXB-specific subclass of <code>ValidationFailureException</code>.
*
* @author Arjen Poutsma
* @see JaxbUtils#convertJaxbException
* @since 3.0
*/
public class JaxbValidationFailureException extends ValidationFailureException {
public JaxbValidationFailureException(ValidationException ex) {
super("JAXB validation exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,6 +45,7 @@ import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.IXMLReader; import org.jibx.runtime.IXMLReader;
import org.jibx.runtime.IXMLWriter; import org.jibx.runtime.IXMLWriter;
import org.jibx.runtime.JiBXException; import org.jibx.runtime.JiBXException;
import org.jibx.runtime.ValidationException;
import org.jibx.runtime.impl.MarshallingContext; import org.jibx.runtime.impl.MarshallingContext;
import org.jibx.runtime.impl.StAXReaderWrapper; import org.jibx.runtime.impl.StAXReaderWrapper;
import org.jibx.runtime.impl.StAXWriter; import org.jibx.runtime.impl.StAXWriter;
@@ -56,21 +57,25 @@ import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.LexicalHandler;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.oxm.AbstractMarshaller; import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.ValidationFailureException;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.support.AbstractMarshaller;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
/** /**
* Implementation of the <code>Marshaller</code> and <code>Unmarshaller</code> interfaces for JiBX. <p/> The typical * Implementation of the <code>Marshaller</code> and <code>Unmarshaller</code> interfaces for JiBX.
* usage will be to set the <code>targetClass</code> and optionally the <code>bindingName</code> property on this bean, *
* and to refer to it. * <p>The typical usage will be to set the <code>targetClass</code> and optionally the
* <code>bindingName</code> property on this bean.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0
* @see org.jibx.runtime.IMarshallingContext * @see org.jibx.runtime.IMarshallingContext
* @see org.jibx.runtime.IUnmarshallingContext * @see org.jibx.runtime.IUnmarshallingContext
* @since 3.0
*/ */
public class JibxMarshaller extends AbstractMarshaller implements InitializingBean { public class JibxMarshaller extends AbstractMarshaller implements InitializingBean {
@@ -78,77 +83,73 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
private String bindingName; private String bindingName;
private IBindingFactory bindingFactory;
private static TransformerFactory transformerFactory = TransformerFactory.newInstance();
private int indent = -1; private int indent = -1;
private String encoding; private String encoding;
private Boolean standalone; private Boolean standalone;
/** private IBindingFactory bindingFactory;
* Sets the optional binding name for this instance.
*/ private TransformerFactory transformerFactory = TransformerFactory.newInstance();
public void setBindingName(String bindingName) {
this.bindingName = bindingName;
}
/** /**
* Sets the target class for this instance. This property is required. * Set the target class for this instance. This property is required.
*/ */
public void setTargetClass(Class targetClass) { public void setTargetClass(Class targetClass) {
this.targetClass = targetClass; this.targetClass = targetClass;
} }
/** /**
* Sets the number of nesting indent spaces. Default is <code>-1</code>, i.e. no indentation. * Set the optional binding name for this instance.
*/
public void setBindingName(String bindingName) {
this.bindingName = bindingName;
}
/**
* Set the number of nesting indent spaces. Default is <code>-1</code>, i.e. no indentation.
*/ */
public void setIndent(int indent) { public void setIndent(int indent) {
this.indent = indent; this.indent = indent;
} }
/** /**
* Sets the document encoding using for marshalling. Default is UTF-8. * Set the document encoding using for marshalling. Default is UTF-8.
*/ */
public void setEncoding(String encoding) { public void setEncoding(String encoding) {
this.encoding = encoding; this.encoding = encoding;
} }
/** /**
* Sets the document standalone flag for marshalling. By default, this flag is not present. * Set the document standalone flag for marshalling. By default, this flag is not present.
*/ */
public void setStandalone(Boolean standalone) { public void setStandalone(Boolean standalone) {
this.standalone = standalone; this.standalone = standalone;
} }
public void afterPropertiesSet() throws Exception {
Assert.notNull(targetClass, "targetClass is required"); public void afterPropertiesSet() throws JiBXException {
if (logger.isInfoEnabled()) { Assert.notNull(this.targetClass, "targetClass is required");
if (StringUtils.hasLength(bindingName)) { if (StringUtils.hasLength(this.bindingName)) {
logger.info("Configured for target class [" + targetClass + "] using binding [" + bindingName + "]"); if (logger.isInfoEnabled()) {
} logger.info("Configured for target class [" + this.targetClass + "] using binding [" + this.bindingName + "]");
else {
logger.info("Configured for target class [" + targetClass + "]");
} }
this.bindingFactory = BindingDirectory.getFactory(this.bindingName, this.targetClass);
} }
try { else {
if (StringUtils.hasLength(bindingName)) { if (logger.isInfoEnabled()) {
bindingFactory = BindingDirectory.getFactory(bindingName, targetClass); logger.info("Configured for target class [" + this.targetClass + "]");
} }
else { this.bindingFactory = BindingDirectory.getFactory(this.targetClass);
bindingFactory = BindingDirectory.getFactory(targetClass);
}
}
catch (JiBXException ex) {
throw new JibxSystemException(ex);
} }
} }
public boolean supports(Class<?> clazz) { public boolean supports(Class<?> clazz) {
Assert.notNull(clazz, "'clazz' must not be null"); Assert.notNull(clazz, "'clazz' must not be null");
String[] mappedClasses = bindingFactory.getMappedClasses(); String[] mappedClasses = this.bindingFactory.getMappedClasses();
String className = clazz.getName(); String className = clazz.getName();
for (String mappedClass : mappedClasses) { for (String mappedClass : mappedClasses) {
if (className.equals(mappedClass)) { if (className.equals(mappedClass)) {
@@ -158,32 +159,15 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
return false; return false;
} }
/**
* Convert the given <code>JiBXException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy. <p/> The default implementation delegates to <code>JibxUtils</code>.
* Can be overridden in subclasses. <p/> A boolean flag is used to indicate whether this exception occurs during
* marshalling or unmarshalling, since JiBX itself does not make this distinction in its exception hierarchy.
*
* @param ex <code>JiBXException</code> that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code> instance
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
*/
public XmlMappingException convertJibxException(JiBXException ex, boolean marshalling) {
return JibxUtils.convertJibxException(ex, marshalling);
}
//
// Supported Marshalling // Supported Marshalling
//
@Override @Override
protected void marshalOutputStream(Object graph, OutputStream outputStream) protected void marshalOutputStream(Object graph, OutputStream outputStream)
throws XmlMappingException, IOException { throws XmlMappingException, IOException {
try { try {
IMarshallingContext marshallingContext = createMarshallingContext(); IMarshallingContext marshallingContext = createMarshallingContext();
marshallingContext.marshalDocument(graph, encoding, standalone, outputStream); marshallingContext.marshalDocument(graph, this.encoding, this.standalone, outputStream);
} }
catch (JiBXException ex) { catch (JiBXException ex) {
throw convertJibxException(ex, true); throw convertJibxException(ex, true);
@@ -194,7 +178,7 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
protected void marshalWriter(Object graph, Writer writer) throws XmlMappingException, IOException { protected void marshalWriter(Object graph, Writer writer) throws XmlMappingException, IOException {
try { try {
IMarshallingContext marshallingContext = createMarshallingContext(); IMarshallingContext marshallingContext = createMarshallingContext();
marshallingContext.marshalDocument(graph, encoding, standalone, writer); marshallingContext.marshalDocument(graph, this.encoding, this.standalone, writer);
} }
catch (JiBXException ex) { catch (JiBXException ex) {
throw convertJibxException(ex, true); throw convertJibxException(ex, true);
@@ -214,9 +198,8 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
} }
} }
//
// Unsupported Marshalling // Unsupported Marshalling
//
@Override @Override
protected void marshalDomNode(Object graph, Node node) throws XmlMappingException { protected void marshalDomNode(Object graph, Node node) throws XmlMappingException {
@@ -225,14 +208,11 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
marshalOutputStream(graph, os); marshalOutputStream(graph, os);
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
Transformer transformer = transformerFactory.newTransformer(); Transformer transformer = this.transformerFactory.newTransformer();
transformer.transform(new StreamSource(is), new DOMResult(node)); transformer.transform(new StreamSource(is), new DOMResult(node));
} }
catch (IOException ex) { catch (Exception ex) {
throw new JibxSystemException(ex); throw new MarshallingFailureException("JiBX marshalling exception", ex);
}
catch (TransformerException ex) {
throw new JibxSystemException(ex);
} }
} }
@@ -244,16 +224,13 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
marshalOutputStream(graph, os); marshalOutputStream(graph, os);
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
Transformer transformer = transformerFactory.newTransformer(); Transformer transformer = this.transformerFactory.newTransformer();
SAXResult saxResult = new SAXResult(contentHandler); SAXResult saxResult = new SAXResult(contentHandler);
saxResult.setLexicalHandler(lexicalHandler); saxResult.setLexicalHandler(lexicalHandler);
transformer.transform(new StreamSource(is), saxResult); transformer.transform(new StreamSource(is), saxResult);
} }
catch (IOException ex) { catch (Exception ex) {
throw new JibxSystemException(ex); throw new MarshallingFailureException("JiBX marshalling exception", ex);
}
catch (TransformerException ex) {
throw new JibxSystemException(ex);
} }
} }
@@ -263,9 +240,8 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
marshalSaxHandlers(graph, contentHandler, null); marshalSaxHandlers(graph, contentHandler, null);
} }
//
// Unmarshalling // Unmarshalling
//
@Override @Override
protected Object unmarshalInputStream(InputStream inputStream) throws XmlMappingException, IOException { protected Object unmarshalInputStream(InputStream inputStream) throws XmlMappingException, IOException {
@@ -309,13 +285,12 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
return unmarshalXmlStreamReader(streamReader); return unmarshalXmlStreamReader(streamReader);
} }
catch (XMLStreamException ex) { catch (XMLStreamException ex) {
throw new JibxSystemException(ex); return new UnmarshallingFailureException("JiBX unmarshalling exception", ex);
} }
} }
//
// Unsupported Unmarshalling // Unsupported Unmarshalling
//
@Override @Override
protected Object unmarshalDomNode(Node node) throws XmlMappingException { protected Object unmarshalDomNode(Node node) throws XmlMappingException {
@@ -326,11 +301,8 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
return unmarshalInputStream(is); return unmarshalInputStream(is);
} }
catch (IOException ex) { catch (Exception ex) {
throw new JibxSystemException(ex); throw new UnmarshallingFailureException("JiBX unmarshalling exception", ex);
}
catch (TransformerException ex) {
throw new JibxSystemException(ex);
} }
} }
@@ -338,41 +310,60 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
throws XmlMappingException, IOException { throws XmlMappingException, IOException {
try { try {
Transformer transformer = transformerFactory.newTransformer(); Transformer transformer = this.transformerFactory.newTransformer();
ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
transformer.transform(new SAXSource(xmlReader, inputSource), new StreamResult(os)); transformer.transform(new SAXSource(xmlReader, inputSource), new StreamResult(os));
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
return unmarshalInputStream(is); return unmarshalInputStream(is);
} }
catch (IOException ex) {
throw new JibxSystemException(ex);
}
catch (TransformerException ex) { catch (TransformerException ex) {
throw new JibxSystemException(ex); throw new UnmarshallingFailureException("JiBX unmarshalling exception", ex);
} }
} }
/** /**
* Creates a new <code>IMarshallingContext</code>, set with the correct indentation. * Create a new <code>IMarshallingContext</code>, configured with the correct indentation.
*
* @return the created marshalling context * @return the created marshalling context
* @throws JiBXException in case of errors * @throws JiBXException in case of errors
*/ */
protected IMarshallingContext createMarshallingContext() throws JiBXException { protected IMarshallingContext createMarshallingContext() throws JiBXException {
IMarshallingContext marshallingContext = bindingFactory.createMarshallingContext(); IMarshallingContext marshallingContext = this.bindingFactory.createMarshallingContext();
marshallingContext.setIndent(indent); marshallingContext.setIndent(this.indent);
return marshallingContext; return marshallingContext;
} }
/** /**
* Creates a new <code>IUnmarshallingContext</code>, set with the correct indentation. * Create a new <code>IUnmarshallingContext</code>.
*
* @return the created unmarshalling context * @return the created unmarshalling context
* @throws JiBXException in case of errors * @throws JiBXException in case of errors
*/ */
protected IUnmarshallingContext createUnmarshallingContext() throws JiBXException { protected IUnmarshallingContext createUnmarshallingContext() throws JiBXException {
return bindingFactory.createUnmarshallingContext(); return this.bindingFactory.createUnmarshallingContext();
} }
/**
* Convert the given <code>JiBXException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy.
* <p>A boolean flag is used to indicate whether this exception occurs during marshalling or
* unmarshalling, since JiBX itself does not make this distinction in its exception hierarchy.
* @param ex <code>JiBXException</code> that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>),
* or unmarshalling (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
*/
public XmlMappingException convertJibxException(JiBXException ex, boolean marshalling) {
if (ex instanceof ValidationException) {
return new ValidationFailureException("JiBX validation exception", ex);
}
else {
if (marshalling) {
return new MarshallingFailureException("JiBX marshalling exception", ex);
}
else {
return new UnmarshallingFailureException("JiBX unmarshalling exception", ex);
}
}
}
} }

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jibx;
import org.jibx.runtime.JiBXException;
import org.springframework.oxm.MarshallingFailureException;
/**
* JiXB-specific subclass of <code>MarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 3.0
*/
public class JibxMarshallingFailureException extends MarshallingFailureException {
public JibxMarshallingFailureException(JiBXException ex) {
super("JiBX marshalling exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jibx;
import org.springframework.oxm.UncategorizedXmlMappingException;
/**
* JiBX-specific subclass of <code>UncategorizedXmlMappingException</code>, for <code>JiBXBException</code>s that cannot
* be distinguished further.
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 3.0
*/
public class JibxSystemException extends UncategorizedXmlMappingException {
public JibxSystemException(Exception ex) {
super(ex.getMessage(), ex);
}
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jibx;
import org.jibx.runtime.JiBXException;
import org.springframework.oxm.UnmarshallingFailureException;
/**
* JiXB-specific subclass of <code>UnmarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 3.0
*/
public class JibxUnmarshallingFailureException extends UnmarshallingFailureException {
public JibxUnmarshallingFailureException(JiBXException ex) {
super("JiBX unmarshalling exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jibx;
import org.jibx.runtime.JiBXException;
import org.jibx.runtime.ValidationException;
import org.springframework.oxm.XmlMappingException;
/**
* Generic utility methods for working with JiBX. Mainly for internal use within the framework.
*
* @author Arjen Poutsma
* @since 3.0
*/
public abstract class JibxUtils {
/**
* Converts the given <code>JiBXException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy. <p/> A boolean flag is used to indicate whether this exception
* occurs during marshalling or unmarshalling, since JiBX itself does not make this distinction in its exception
* hierarchy.
*
* @param ex <code>JiBXException</code> that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
*/
public static XmlMappingException convertJibxException(JiBXException ex, boolean marshalling) {
if (ex instanceof ValidationException) {
return new JibxValidationFailureException((ValidationException) ex);
}
else {
if (marshalling) {
return new JibxMarshallingFailureException(ex);
}
else {
return new JibxUnmarshallingFailureException(ex);
}
}
}
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jibx;
import org.jibx.runtime.ValidationException;
import org.springframework.oxm.ValidationFailureException;
/**
* JAXB-specific subclass of <code>ValidationFailureException</code>.
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 3.0
*/
public class JibxValidationFailureException extends ValidationFailureException {
public JibxValidationFailureException(ValidationException ex) {
super("JiBX validation exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2007 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,44 +19,43 @@ package org.springframework.oxm.mime;
import javax.activation.DataHandler; import javax.activation.DataHandler;
/** /**
* Represents a container for MIME attachments. Concrete implementations might adapt a SOAPMesage, or an email message. * Represents a container for MIME attachments
* Concrete implementations might adapt a SOAPMessage or an email message.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
* @since 3.0 * @since 3.0
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
*/ */
public interface MimeContainer { public interface MimeContainer {
/** /**
* Indicates whether this container is a XOP package. * Indicate whether this container is a XOP package.
* * @return <code>true</code> when the constraints specified in
* @return <code>true</code> when the constraints specified in <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#identifying_xop_documents">Identifying * <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#identifying_xop_documents">Identifying XOP Documents</a>
* XOP Documents</a> are met. * are met
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a> * @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a>
*/ */
boolean isXopPackage(); boolean isXopPackage();
/** /**
* Turns this message into a XOP package. * Turn this message into a XOP package.
* * @return <code>true</code> when the message actually is a XOP package
* @return <code>true</code> when the message is a XOP package
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a> * @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a>
*/ */
boolean convertToXopPackage(); boolean convertToXopPackage();
/** /**
* Adds the given data handler as an attachment to this container. * Add the given data handler as an attachment to this container.
* * @param contentId the content id of the attachment
* @param contentId the content id of the attachment
* @param dataHandler the data handler containing the data of the attachment * @param dataHandler the data handler containing the data of the attachment
*/ */
void addAttachment(String contentId, DataHandler dataHandler); void addAttachment(String contentId, DataHandler dataHandler);
/** /**
* Returns the attachment with the given content id, or <code>null</code> if not found. * Return the attachment with the given content id, or <code>null</code> if not found.
*
* @param contentId the content id * @param contentId the content id
* @return the attachment, as a data handler * @return the attachment, as a data handler
*/ */
DataHandler getAttachment(String contentId); DataHandler getAttachment(String contentId);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2007 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,28 +23,25 @@ import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
/** /**
* Subinterface of {@link Marshaller} that can use MIME attachments to optimize storage of binary data. Attachments can * Subinterface of {@link Marshaller} that can use MIME attachments to optimize
* be added as MTOM, XOP, or SwA. * storage of binary data. Attachments can be added as MTOM, XOP, or SwA.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @see <a href="http://www.w3.org/TR/2004/WD-soap12-mtom-20040608/">SOAP Message Transmission Optimization
* Mechanism</a>
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
* @since 3.0 * @since 3.0
* @see <a href="http://www.w3.org/TR/2004/WD-soap12-mtom-20040608/">SOAP Message Transmission Optimization Mechanism</a>
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
*/ */
public interface MimeMarshaller extends Marshaller { public interface MimeMarshaller extends Marshaller {
/** /**
* Marshals the object graph with the given root into the provided {@link Result}, writing binary data to a {@link * Marshals the object graph with the given root into the provided {@link Result},
* MimeContainer}. * writing binary data to a {@link MimeContainer}.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal * @param result the result to marshal to
* @param result the result to marshal to
* @param mimeContainer the MIME container to write extracted binary content to * @param mimeContainer the MIME container to write extracted binary content to
* @throws XmlMappingException if the given object cannot be marshalled to the result * @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
*/ */
void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException, IOException; void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException, IOException;
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2007 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,26 +23,25 @@ import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
/** /**
* Subinterface of {@link org.springframework.oxm.Marshaller} that can use MIME attachments to optimize storage of * Subinterface of {@link org.springframework.oxm.Marshaller} that can use MIME attachments
* binary data. Attachments can be added as MTOM, XOP, or SwA. * to optimize storage of binary data. Attachments can be added as MTOM, XOP, or SwA.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @see <a href="http://www.w3.org/TR/2004/WD-soap12-mtom-20040608/">SOAP Message Transmission Optimization
* Mechanism</a>
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
* @since 3.0 * @since 3.0
* @see <a href="http://www.w3.org/TR/2004/WD-soap12-mtom-20040608/">SOAP Message Transmission Optimization Mechanism</a>
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
*/ */
public interface MimeUnmarshaller extends Unmarshaller { public interface MimeUnmarshaller extends Unmarshaller {
/** /**
* Unmarshals the given provided {@link Source} into an object graph, reading binary attachments from a {@link * Unmarshals the given provided {@link Source} into an object graph,
* MimeContainer}. * reading binary attachments from a {@link MimeContainer}.
* * @param source the source to marshal from
* @param source the source to marshal from
* @param mimeContainer the MIME container to read extracted binary content from * @param mimeContainer the MIME container to read extracted binary content from
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object * @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IOException if an I/O Exception occurs * @throws IOException if an I/O Exception occurs
*/ */
Object unmarshal(Source source, MimeContainer mimeContainer) throws XmlMappingException, IOException; Object unmarshal(Source source, MimeContainer mimeContainer) throws XmlMappingException, IOException;
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm.support;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -48,15 +48,20 @@ import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
/** /**
* Abstract implementation of the <code>Marshaller</code> and <code>Unmarshaller</code> interface. This implementation * Abstract implementation of the <code>Marshaller</code> and <code>Unmarshaller</code> interface.
* inspects the given <code>Source</code> or <code>Result</code>, and defers further handling to overridable template * This implementation inspects the given <code>Source</code> or <code>Result</code>, and defers
* methods. * further handling to overridable template methods.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0 * @since 3.0
*/ */
public abstract class AbstractMarshaller implements Marshaller, Unmarshaller { public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
@@ -66,22 +71,24 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
private DocumentBuilderFactory documentBuilderFactory; private DocumentBuilderFactory documentBuilderFactory;
private final Object documentBuilderFactoryMonitor = new Object();
/** /**
* Marshals the object graph with the given root into the provided <code>javax.xml.transform.Result</code>. <p/> This * Marshals the object graph with the given root into the provided <code>javax.xml.transform.Result</code>.
* implementation inspects the given result, and calls <code>marshalDomResult</code>, <code>marshalSaxResult</code>, or * <p>This implementation inspects the given result, and calls <code>marshalDomResult</code>,
* <code>marshalStreamResult</code>. * <code>marshalSaxResult</code>, or <code>marshalStreamResult</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param result the result to marshal to * @param result the result to marshal to
* @throws XmlMappingException if the given object cannot be marshalled to the result * @throws IOException if an I/O exception occurs
* @throws IOException if an I/O exception occurs * @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if <code>result</code> if neither a <code>DOMResult</code>, <code>SAXResult</code>, * @throws IllegalArgumentException if <code>result</code> if neither a <code>DOMResult</code>,
* <code>StreamResult</code> * a <code>SAXResult</code>, nor a <code>StreamResult</code>
* @see #marshalDomResult(Object,javax.xml.transform.dom.DOMResult) * @see #marshalDomResult(Object, javax.xml.transform.dom.DOMResult)
* @see #marshalSaxResult(Object,javax.xml.transform.sax.SAXResult) * @see #marshalSaxResult(Object, javax.xml.transform.sax.SAXResult)
* @see #marshalStreamResult(Object,javax.xml.transform.stream.StreamResult) * @see #marshalStreamResult(Object, javax.xml.transform.stream.StreamResult)
*/ */
public final void marshal(Object graph, Result result) throws XmlMappingException, IOException { public final void marshal(Object graph, Result result) throws IOException, XmlMappingException {
if (result instanceof DOMResult) { if (result instanceof DOMResult) {
marshalDomResult(graph, (DOMResult) result); marshalDomResult(graph, (DOMResult) result);
} }
@@ -100,21 +107,20 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Unmarshals the given provided <code>javax.xml.transform.Source</code> into an object graph. <p/> This implementation * Unmarshals the given provided <code>javax.xml.transform.Source</code> into an object graph.
* inspects the given result, and calls <code>unmarshalDomSource</code>, <code>unmarshalSaxSource</code>, or * <p>This implementation inspects the given result, and calls <code>unmarshalDomSource</code>,
* <code>unmarshalStreamSource</code>. * <code>unmarshalSaxSource</code>, or <code>unmarshalStreamSource</code>.
*
* @param source the source to marshal from * @param source the source to marshal from
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object * @throws IOException if an I/O Exception occurs
* @throws IOException if an I/O Exception occurs * @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IllegalArgumentException if <code>source</code> is neither a <code>DOMSource</code>, a * @throws IllegalArgumentException if <code>source</code> is neither a <code>DOMSource</code>,
* <code>SAXSource</code>, nor a <code>StreamSource</code> * a <code>SAXSource</code>, nor a <code>StreamSource</code>
* @see #unmarshalDomSource(javax.xml.transform.dom.DOMSource) * @see #unmarshalDomSource(javax.xml.transform.dom.DOMSource)
* @see #unmarshalSaxSource(javax.xml.transform.sax.SAXSource) * @see #unmarshalSaxSource(javax.xml.transform.sax.SAXSource)
* @see #unmarshalStreamSource(javax.xml.transform.stream.StreamSource) * @see #unmarshalStreamSource(javax.xml.transform.stream.StreamSource)
*/ */
public final Object unmarshal(Source source) throws XmlMappingException, IOException { public final Object unmarshal(Source source) throws IOException, XmlMappingException {
if (source instanceof DOMSource) { if (source instanceof DOMSource) {
return unmarshalDomSource((DOMSource) source); return unmarshalDomSource((DOMSource) source);
} }
@@ -133,24 +139,24 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Create a <code>DocumentBuilder</code> that this marshaller will use for creating DOM documents when passed an empty * Create a <code>DocumentBuilder</code> that this marshaller will use for creating
* <code>DOMSource</code>. Can be overridden in subclasses, adding further initialization of the builder. * DOM documents when passed an empty <code>DOMSource</code>.
* * <p>Can be overridden in subclasses, adding further initialization of the builder.
* @param factory the <code>DocumentBuilderFactory</code> that the DocumentBuilder should be created with * @param factory the <code>DocumentBuilderFactory</code> that the DocumentBuilder should be created with
* @return the <code>DocumentBuilder</code> * @return the <code>DocumentBuilder</code>
* @throws javax.xml.parsers.ParserConfigurationException * @throws ParserConfigurationException if thrown by JAXP methods
* if thrown by JAXP methods
*/ */
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory) protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory)
throws ParserConfigurationException { throws ParserConfigurationException {
return factory.newDocumentBuilder(); return factory.newDocumentBuilder();
} }
/** /**
* Create a <code>DocumentBuilder</code> that this marshaller will use for creating DOM documents when passed an empty * Create a <code>DocumentBuilder</code> that this marshaller will use for creating
* <code>DOMSource</code>. The resulting <code>DocumentBuilderFactory</code> is cached, so this method will only be * DOM documents when passed an empty <code>DOMSource</code>.
* called once. * <p>The resulting <code>DocumentBuilderFactory</code> is cached, so this method
* * will only be called once.
* @return the DocumentBuilderFactory * @return the DocumentBuilderFactory
* @throws ParserConfigurationException if thrown by JAXP methods * @throws ParserConfigurationException if thrown by JAXP methods
*/ */
@@ -163,7 +169,6 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
/** /**
* Create a <code>XMLReader</code> that this marshaller will when passed an empty <code>SAXSource</code>. * Create a <code>XMLReader</code> that this marshaller will when passed an empty <code>SAXSource</code>.
*
* @return the XMLReader * @return the XMLReader
* @throws SAXException if thrown by JAXP methods * @throws SAXException if thrown by JAXP methods
*/ */
@@ -171,18 +176,17 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
return XMLReaderFactory.createXMLReader(); return XMLReaderFactory.createXMLReader();
} }
//
// Marshalling // Marshalling
//
/** /**
* Template method for handling <code>DOMResult</code>s. This implementation defers to <code>marshalDomNode</code>. * Template method for handling <code>DOMResult</code>s.
* * <p>This implementation delegates to <code>marshalDomNode</code>.
* @param graph the root of the object graph to marshal * @param graph the root of the object graph to marshal
* @param domResult the <code>DOMResult</code> * @param domResult the <code>DOMResult</code>
* @throws XmlMappingException if the given object cannot be marshalled to the result * @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if the <code>domResult</code> is empty * @throws IllegalArgumentException if the <code>domResult</code> is empty
* @see #marshalDomNode(Object,org.w3c.dom.Node) * @see #marshalDomNode(Object, org.w3c.dom.Node)
*/ */
protected void marshalDomResult(Object graph, DOMResult domResult) throws XmlMappingException { protected void marshalDomResult(Object graph, DOMResult domResult) throws XmlMappingException {
Assert.notNull(domResult.getNode(), "DOMResult does not contain Node"); Assert.notNull(domResult.getNode(), "DOMResult does not contain Node");
@@ -190,13 +194,13 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Template method for handling <code>StaxResult</code>s. This implementation defers to * Template method for handling <code>StaxResult</code>s.
* <code>marshalXMLSteamWriter</code>, or <code>marshalXMLEventConsumer</code>, depending on what is contained in the * <p>This implementation delegates to <code>marshalXMLSteamWriter</code> or
* <code>marshalXMLEventConsumer</code>, depending on what is contained in the
* <code>StaxResult</code>. * <code>StaxResult</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param staxResult a Spring {@link org.springframework.util.xml.StaxSource} or JAXP 1.4 {@link StAXSource} * @param staxResult a Spring {@link org.springframework.util.xml.StaxSource} or JAXP 1.4 {@link StAXSource}
* @throws XmlMappingException if the given object cannot be marshalled to the result * @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if the <code>domResult</code> is empty * @throws IllegalArgumentException if the <code>domResult</code> is empty
* @see #marshalDomNode(Object,org.w3c.dom.Node) * @see #marshalDomNode(Object,org.w3c.dom.Node)
*/ */
@@ -217,13 +221,12 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Template method for handling <code>SAXResult</code>s. This implementation defers to * Template method for handling <code>SAXResult</code>s.
* <code>marshalSaxHandlers</code>. * <p>This implementation delegates to <code>marshalSaxHandlers</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param saxResult the <code>SAXResult</code> * @param saxResult the <code>SAXResult</code>
* @throws XmlMappingException if the given object cannot be marshalled to the result * @throws XmlMappingException if the given object cannot be marshalled to the result
* @see #marshalSaxHandlers(Object,org.xml.sax.ContentHandler,org.xml.sax.ext.LexicalHandler) * @see #marshalSaxHandlers(Object, org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler)
*/ */
protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException { protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException {
ContentHandler contentHandler = saxResult.getHandler(); ContentHandler contentHandler = saxResult.getHandler();
@@ -233,19 +236,19 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Template method for handling <code>StreamResult</code>s. This implementation defers to * Template method for handling <code>StreamResult</code>s.
* <code>marshalOutputStream</code>, or <code>marshalWriter</code>, depending on what is contained in the * <p>This implementation delegates to <code>marshalOutputStream</code> or <code>marshalWriter</code>,
* <code>StreamResult</code> * depending on what is contained in the <code>StreamResult</code>
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param streamResult the <code>StreamResult</code> * @param streamResult the <code>StreamResult</code>
* @throws IOException if an I/O Exception occurs * @throws IOException if an I/O Exception occurs
* @throws XmlMappingException if the given object cannot be marshalled to the result * @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if <code>streamResult</code> contains neither <code>OutputStream</code> nor * @throws IllegalArgumentException if <code>streamResult</code> does neither
* <code>Writer</code>. * contain an <code>OutputStream</code> nor a <code>Writer</code>
*/ */
protected void marshalStreamResult(Object graph, StreamResult streamResult) protected void marshalStreamResult(Object graph, StreamResult streamResult)
throws XmlMappingException, IOException { throws XmlMappingException, IOException {
if (streamResult.getOutputStream() != null) { if (streamResult.getOutputStream() != null) {
marshalOutputStream(graph, streamResult.getOutputStream()); marshalOutputStream(graph, streamResult.getOutputStream());
} }
@@ -257,27 +260,29 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
} }
//
// Unmarshalling // Unmarshalling
//
/** /**
* Template method for handling <code>DOMSource</code>s. This implementation defers to <code>unmarshalDomNode</code>. * Template method for handling <code>DOMSource</code>s.
* If the given source is empty, an empty source <code>Document</code> will be created as a placeholder. * <p>This implementation delegates to <code>unmarshalDomNode</code>.
* * If the given source is empty, an empty source <code>Document</code>
* will be created as a placeholder.
* @param domSource the <code>DOMSource</code> * @param domSource the <code>DOMSource</code>
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IllegalArgumentException if the <code>domSource</code> is empty * @throws IllegalArgumentException if the <code>domSource</code> is empty
* @throws XmlMappingException if the given source cannot be mapped to an object
* @see #unmarshalDomNode(org.w3c.dom.Node) * @see #unmarshalDomNode(org.w3c.dom.Node)
*/ */
protected Object unmarshalDomSource(DOMSource domSource) throws XmlMappingException { protected Object unmarshalDomSource(DOMSource domSource) throws XmlMappingException {
if (domSource.getNode() == null) { if (domSource.getNode() == null) {
try { try {
if (documentBuilderFactory == null) { synchronized (this.documentBuilderFactoryMonitor) {
documentBuilderFactory = createDocumentBuilderFactory(); if (this.documentBuilderFactory == null) {
this.documentBuilderFactory = createDocumentBuilderFactory();
}
} }
DocumentBuilder documentBuilder = createDocumentBuilder(documentBuilderFactory); DocumentBuilder documentBuilder = createDocumentBuilder(this.documentBuilderFactory);
domSource.setNode(documentBuilder.newDocument()); domSource.setNode(documentBuilder.newDocument());
} }
catch (ParserConfigurationException ex) { catch (ParserConfigurationException ex) {
@@ -289,9 +294,9 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Template method for handling <code>StaxSource</code>s. This implementation defers to * Template method for handling <code>StaxSource</code>s.
* <code>unmarshalXmlStreamReader</code>, or <code>unmarshalXmlEventReader</code>. * <p>This implementation delegates to <code>unmarshalXmlStreamReader</code> or
* * <code>unmarshalXmlEventReader</code>.
* @param staxSource the <code>StaxSource</code> * @param staxSource the <code>StaxSource</code>
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object * @throws XmlMappingException if the given source cannot be mapped to an object
@@ -313,14 +318,13 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Template method for handling <code>SAXSource</code>s. This implementation defers to * Template method for handling <code>SAXSource</code>s.
* <code>unmarshalSaxReader</code>. * <p>This implementation delegates to <code>unmarshalSaxReader</code>.
*
* @param saxSource the <code>SAXSource</code> * @param saxSource the <code>SAXSource</code>
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object * @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IOException if an I/O Exception occurs * @throws IOException if an I/O Exception occurs
* @see #unmarshalSaxReader(org.xml.sax.XMLReader,org.xml.sax.InputSource) * @see #unmarshalSaxReader(org.xml.sax.XMLReader, org.xml.sax.InputSource)
*/ */
protected Object unmarshalSaxSource(SAXSource saxSource) throws XmlMappingException, IOException { protected Object unmarshalSaxSource(SAXSource saxSource) throws XmlMappingException, IOException {
if (saxSource.getXMLReader() == null) { if (saxSource.getXMLReader() == null) {
@@ -328,8 +332,7 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
saxSource.setXMLReader(createXmlReader()); saxSource.setXMLReader(createXmlReader());
} }
catch (SAXException ex) { catch (SAXException ex) {
throw new UnmarshallingFailureException("Could not create XMLReader for SAXSource: " + ex.getMessage(), throw new UnmarshallingFailureException("Could not create XMLReader for SAXSource", ex);
ex);
} }
} }
if (saxSource.getInputSource() == null) { if (saxSource.getInputSource() == null) {
@@ -339,12 +342,11 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
/** /**
* Template method for handling <code>StreamSource</code>s. This implementation defers to * Template method for handling <code>StreamSource</code>s.
* <code>unmarshalInputStream</code>, or <code>unmarshalReader</code>. * <p>This implementation defers to <code>unmarshalInputStream</code> or <code>unmarshalReader</code>.
*
* @param streamSource the <code>StreamSource</code> * @param streamSource the <code>StreamSource</code>
* @return the object graph * @return the object graph
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
* @throws XmlMappingException if the given source cannot be mapped to an object * @throws XmlMappingException if the given source cannot be mapped to an object
*/ */
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException { protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
@@ -359,37 +361,35 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
} }
} }
//
// Abstract template methods // Abstract template methods
//
/** /**
* Abstract template method for marshalling the given object graph to a DOM <code>Node</code>. <p/> In practice, node * Abstract template method for marshalling the given object graph to a DOM <code>Node</code>.
* is be a <code>Document</code> node, a <code>DocumentFragment</code> node, or a <code>Element</code> node. In other * <p>In practice, node is be a <code>Document</code> node, a <code>DocumentFragment</code> node,
* words, a node that accepts children. * or a <code>Element</code> node. In other words, a node that accepts children.
*
* @param graph the root of the object graph to marshal * @param graph the root of the object graph to marshal
* @param node The DOM node that will contain the result tree * @param node the DOM node that will contain the result tree
* @throws XmlMappingException if the given object cannot be marshalled to the DOM node * @throws XmlMappingException if the given object cannot be marshalled to the DOM node
* @see org.w3c.dom.Document * @see org.w3c.dom.Document
* @see org.w3c.dom.DocumentFragment * @see org.w3c.dom.DocumentFragment
* @see org.w3c.dom.Element * @see org.w3c.dom.Element
*/ */
protected abstract void marshalDomNode(Object graph, Node node) throws XmlMappingException; protected abstract void marshalDomNode(Object graph, Node node)
throws XmlMappingException;
/** /**
* Abstract template method for marshalling the given object to a StAX <code>XMLEventWriter</code>. * Abstract template method for marshalling the given object to a StAX <code>XMLEventWriter</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param eventWriter the <code>XMLEventWriter</code> to write to * @param eventWriter the <code>XMLEventWriter</code> to write to
* @throws XmlMappingException if the given object cannot be marshalled to the DOM node * @throws XmlMappingException if the given object cannot be marshalled to the DOM node
*/ */
protected abstract void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter) throws XmlMappingException; protected abstract void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter)
throws XmlMappingException;
/** /**
* Abstract template method for marshalling the given object to a StAX <code>XMLStreamWriter</code>. * Abstract template method for marshalling the given object to a StAX <code>XMLStreamWriter</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param streamWriter the <code>XMLStreamWriter</code> to write to * @param streamWriter the <code>XMLStreamWriter</code> to write to
* @throws XmlMappingException if the given object cannot be marshalled to the DOM node * @throws XmlMappingException if the given object cannot be marshalled to the DOM node
*/ */
@@ -398,41 +398,38 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
/** /**
* Abstract template method for marshalling the given object graph to a <code>OutputStream</code>. * Abstract template method for marshalling the given object graph to a <code>OutputStream</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param outputStream the <code>OutputStream</code> to write to * @param outputStream the <code>OutputStream</code> to write to
* @throws XmlMappingException if the given object cannot be marshalled to the writer * @throws XmlMappingException if the given object cannot be marshalled to the writer
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
*/ */
protected abstract void marshalOutputStream(Object graph, OutputStream outputStream) protected abstract void marshalOutputStream(Object graph, OutputStream outputStream)
throws XmlMappingException, IOException; throws XmlMappingException, IOException;
/** /**
* Abstract template method for marshalling the given object graph to a SAX <code>ContentHandler</code>. * Abstract template method for marshalling the given object graph to a SAX <code>ContentHandler</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param contentHandler the SAX <code>ContentHandler</code> * @param contentHandler the SAX <code>ContentHandler</code>
* @param lexicalHandler the SAX2 <code>LexicalHandler</code>. Can be <code>null</code>. * @param lexicalHandler the SAX2 <code>LexicalHandler</code>. Can be <code>null</code>.
* @throws XmlMappingException if the given object cannot be marshalled to the handlers * @throws XmlMappingException if the given object cannot be marshalled to the handlers
*/ */
protected abstract void marshalSaxHandlers(Object graph, protected abstract void marshalSaxHandlers(
ContentHandler contentHandler, Object graph, ContentHandler contentHandler, LexicalHandler lexicalHandler)
LexicalHandler lexicalHandler) throws XmlMappingException; throws XmlMappingException;
/** /**
* Abstract template method for marshalling the given object graph to a <code>Writer</code>. * Abstract template method for marshalling the given object graph to a <code>Writer</code>.
* * @param graph the root of the object graph to marshal
* @param graph the root of the object graph to marshal
* @param writer the <code>Writer</code> to write to * @param writer the <code>Writer</code> to write to
* @throws XmlMappingException if the given object cannot be marshalled to the writer * @throws XmlMappingException if the given object cannot be marshalled to the writer
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
*/ */
protected abstract void marshalWriter(Object graph, Writer writer) throws XmlMappingException, IOException; protected abstract void marshalWriter(Object graph, Writer writer)
throws XmlMappingException, IOException;
/** /**
* Abstract template method for unmarshalling from a given DOM <code>Node</code>. * Abstract template method for unmarshalling from a given DOM <code>Node</code>.
* * @param node the DOM node that contains the objects to be unmarshalled
* @param node The DOM node that contains the objects to be unmarshalled
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given DOM node cannot be mapped to an object * @throws XmlMappingException if the given DOM node cannot be mapped to an object
*/ */
@@ -440,51 +437,52 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
/** /**
* Abstract template method for unmarshalling from a given Stax <code>XMLEventReader</code>. * Abstract template method for unmarshalling from a given Stax <code>XMLEventReader</code>.
* * @param eventReader the <code>XMLEventReader</code> to read from
* @param eventReader The <code>XMLEventReader</code> to read from
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given event reader cannot be converted to an object * @throws XmlMappingException if the given event reader cannot be converted to an object
*/ */
protected abstract Object unmarshalXmlEventReader(XMLEventReader eventReader) throws XmlMappingException; protected abstract Object unmarshalXmlEventReader(XMLEventReader eventReader)
throws XmlMappingException;
/** /**
* Abstract template method for unmarshalling from a given Stax <code>XMLStreamReader</code>. * Abstract template method for unmarshalling from a given Stax <code>XMLStreamReader</code>.
* * @param streamReader the <code>XMLStreamReader</code> to read from
* @param streamReader The <code>XMLStreamReader</code> to read from
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given stream reader cannot be converted to an object * @throws XmlMappingException if the given stream reader cannot be converted to an object
*/ */
protected abstract Object unmarshalXmlStreamReader(XMLStreamReader streamReader) throws XmlMappingException; protected abstract Object unmarshalXmlStreamReader(XMLStreamReader streamReader)
throws XmlMappingException;
/** /**
* Abstract template method for unmarshalling from a given <code>InputStream</code>. * Abstract template method for unmarshalling from a given <code>InputStream</code>.
*
* @param inputStream the <code>InputStreamStream</code> to read from * @param inputStream the <code>InputStreamStream</code> to read from
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given stream cannot be converted to an object * @throws XmlMappingException if the given stream cannot be converted to an object
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
*/ */
protected abstract Object unmarshalInputStream(InputStream inputStream) throws XmlMappingException, IOException; protected abstract Object unmarshalInputStream(InputStream inputStream)
throws XmlMappingException, IOException;
/** /**
* Abstract template method for unmarshalling from a given <code>Reader</code>. * Abstract template method for unmarshalling from a given <code>Reader</code>.
*
* @param reader the <code>Reader</code> to read from * @param reader the <code>Reader</code> to read from
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given reader cannot be converted to an object * @throws XmlMappingException if the given reader cannot be converted to an object
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
*/ */
protected abstract Object unmarshalReader(Reader reader) throws XmlMappingException, IOException; protected abstract Object unmarshalReader(Reader reader)
throws XmlMappingException, IOException;
/** /**
* Abstract template method for unmarshalling using a given SAX <code>XMLReader</code> and <code>InputSource</code>. * Abstract template method for unmarshalling using a given SAX <code>XMLReader</code>
* * and <code>InputSource</code>.
* @param xmlReader the SAX <code>XMLReader</code> to parse with * @param xmlReader the SAX <code>XMLReader</code> to parse with
* @param inputSource the input source to parse from * @param inputSource the input source to parse from
* @return the object graph * @return the object graph
* @throws XmlMappingException if the given reader and input source cannot be converted to an object * @throws XmlMappingException if the given reader and input source cannot be converted to an object
* @throws java.io.IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
*/ */
protected abstract Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) protected abstract Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
throws XmlMappingException, IOException; throws XmlMappingException, IOException;
} }

View File

@@ -28,7 +28,6 @@ import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException; import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.LexicalHandler;
@@ -37,8 +36,8 @@ import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* {@link Source} implementation that uses a {@link Marshaller}.Can be constructed with a <code>Marshaller</code> and an * {@link Source} implementation that uses a {@link Marshaller}.Can be constructed with a
* object to be marshalled. * <code>Marshaller</code> and an object to be marshalled.
* *
* <p>Even though <code>MarshallingSource</code> extends from <code>SAXSource</code>, calling the methods of * <p>Even though <code>MarshallingSource</code> extends from <code>SAXSource</code>, calling the methods of
* <code>SAXSource</code> is <strong>not supported</strong>. In general, the only supported operation on this class is * <code>SAXSource</code> is <strong>not supported</strong>. In general, the only supported operation on this class is
@@ -47,8 +46,8 @@ import org.springframework.util.Assert;
* <code>UnsupportedOperationException</code>s. * <code>UnsupportedOperationException</code>s.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @see javax.xml.transform.Transformer
* @since 3.0 * @since 3.0
* @see javax.xml.transform.Transformer
*/ */
public class MarshallingSource extends SAXSource { public class MarshallingSource extends SAXSource {
@@ -56,11 +55,11 @@ public class MarshallingSource extends SAXSource {
private final Object content; private final Object content;
/** /**
* Creates a new <code>MarshallingSource</code> with the given marshaller and content. * Create a new <code>MarshallingSource</code> with the given marshaller and content.
*
* @param marshaller the marshaller to use * @param marshaller the marshaller to use
* @param content the object to be marshalled * @param content the object to be marshalled
*/ */
public MarshallingSource(Marshaller marshaller, Object content) { public MarshallingSource(Marshaller marshaller, Object content) {
super(new MarshallingXMLReader(marshaller, content), new InputSource()); super(new MarshallingXMLReader(marshaller, content), new InputSource());
@@ -70,20 +69,23 @@ public class MarshallingSource extends SAXSource {
this.content = content; this.content = content;
} }
/** Returns the <code>Marshaller</code> used by this <code>MarshallingSource</code>. */
/**
* Return the <code>Marshaller</code> used by this <code>MarshallingSource</code>.
*/
public Marshaller getMarshaller() { public Marshaller getMarshaller() {
return marshaller; return this.marshaller;
} }
/** Returns the object to be marshalled. */ /**
* Return the object to be marshalled.
*/
public Object getContent() { public Object getContent() {
return content; return this.content;
} }
/** /**
* Throws a <code>UnsupportedOperationException</code>. * Throws a <code>UnsupportedOperationException</code>.
*
* @throws UnsupportedOperationException always
*/ */
@Override @Override
public void setInputSource(InputSource inputSource) { public void setInputSource(InputSource inputSource) {
@@ -92,14 +94,13 @@ public class MarshallingSource extends SAXSource {
/** /**
* Throws a <code>UnsupportedOperationException</code>. * Throws a <code>UnsupportedOperationException</code>.
*
* @throws UnsupportedOperationException always
*/ */
@Override @Override
public void setXMLReader(XMLReader reader) { public void setXMLReader(XMLReader reader) {
throw new UnsupportedOperationException("setXMLReader is not supported"); throw new UnsupportedOperationException("setXMLReader is not supported");
} }
private static class MarshallingXMLReader implements XMLReader { private static class MarshallingXMLReader implements XMLReader {
private final Marshaller marshaller; private final Marshaller marshaller;
@@ -123,51 +124,51 @@ public class MarshallingSource extends SAXSource {
this.content = content; this.content = content;
} }
public ContentHandler getContentHandler() {
return contentHandler;
}
public void setContentHandler(ContentHandler contentHandler) { public void setContentHandler(ContentHandler contentHandler) {
this.contentHandler = contentHandler; this.contentHandler = contentHandler;
} }
public ContentHandler getContentHandler() {
return this.contentHandler;
}
public void setDTDHandler(DTDHandler dtdHandler) { public void setDTDHandler(DTDHandler dtdHandler) {
this.dtdHandler = dtdHandler; this.dtdHandler = dtdHandler;
} }
public DTDHandler getDTDHandler() { public DTDHandler getDTDHandler() {
return dtdHandler; return this.dtdHandler;
}
public EntityResolver getEntityResolver() {
return entityResolver;
} }
public void setEntityResolver(EntityResolver entityResolver) { public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver; this.entityResolver = entityResolver;
} }
public ErrorHandler getErrorHandler() { public EntityResolver getEntityResolver() {
return errorHandler; return this.entityResolver;
} }
public void setErrorHandler(ErrorHandler errorHandler) { public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
} }
public ErrorHandler getErrorHandler() {
return this.errorHandler;
}
protected LexicalHandler getLexicalHandler() { protected LexicalHandler getLexicalHandler() {
return lexicalHandler; return this.lexicalHandler;
} }
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { public boolean getFeature(String name) throws SAXNotRecognizedException {
throw new SAXNotRecognizedException(name); throw new SAXNotRecognizedException(name);
} }
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { public void setFeature(String name, boolean value) throws SAXNotRecognizedException {
throw new SAXNotRecognizedException(name); throw new SAXNotRecognizedException(name);
} }
public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { public Object getProperty(String name) throws SAXNotRecognizedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) { if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
return lexicalHandler; return lexicalHandler;
} }
@@ -176,20 +177,20 @@ public class MarshallingSource extends SAXSource {
} }
} }
public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { public void setProperty(String name, Object value) throws SAXNotRecognizedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) { if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
lexicalHandler = (LexicalHandler) value; this.lexicalHandler = (LexicalHandler) value;
} }
else { else {
throw new SAXNotRecognizedException(name); throw new SAXNotRecognizedException(name);
} }
} }
public void parse(InputSource input) throws IOException, SAXException { public void parse(InputSource input) throws SAXException {
parse(); parse();
} }
public void parse(String systemId) throws IOException, SAXException { public void parse(String systemId) throws SAXException {
parse(); parse();
} }
@@ -197,18 +198,19 @@ public class MarshallingSource extends SAXSource {
SAXResult result = new SAXResult(getContentHandler()); SAXResult result = new SAXResult(getContentHandler());
result.setLexicalHandler(getLexicalHandler()); result.setLexicalHandler(getLexicalHandler());
try { try {
marshaller.marshal(content, result); this.marshaller.marshal(this.content, result);
} }
catch (IOException ex) { catch (IOException ex) {
SAXParseException saxException = new SAXParseException(ex.getMessage(), null, null, -1, -1, ex); SAXParseException saxException = new SAXParseException(ex.getMessage(), null, null, -1, -1, ex);
if (getErrorHandler() != null) { ErrorHandler errorHandler = getErrorHandler();
getErrorHandler().fatalError(saxException); if (errorHandler != null) {
errorHandler.fatalError(saxException);
} }
else { else {
throw saxException; throw saxException;
} }
} }
} }
} }
} }

View File

@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.util.xml; package org.springframework.oxm.support;
import java.io.IOException; import java.io.IOException;
@@ -26,14 +26,14 @@ import org.springframework.core.io.Resource;
* Convenient utility methods for dealing with SAX. * Convenient utility methods for dealing with SAX.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0 * @since 3.0
*/ */
public abstract class SaxUtils { public abstract class SaxResourceUtils {
/** /**
* Creates a SAX <code>InputSource</code> from the given resource. Sets the system identifier to the resource's * Create a SAX <code>InputSource</code> from the given resource.
* <code>URL</code>, if available. * <p>Sets the system identifier to the resource's <code>URL</code>, if available.
*
* @param resource the resource * @param resource the resource
* @return the input source created from the resource * @return the input source created from the resource
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
@@ -46,12 +46,15 @@ public abstract class SaxUtils {
return inputSource; return inputSource;
} }
/** Retrieves the URL from the given resource as System ID. Returns <code>null</code> if it cannot be openened. */ /**
* Retrieve the URL from the given resource as System ID.
* <p>Returns <code>null</code> if it cannot be opened.
*/
private static String getSystemId(Resource resource) { private static String getSystemId(Resource resource) {
try { try {
return resource.getURI().toString(); return resource.getURI().toString();
} }
catch (IOException e) { catch (IOException ex) {
return null; return null;
} }
} }

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xmlbeans; package org.springframework.oxm.xmlbeans;
import java.io.IOException; import java.io.IOException;
@@ -6,7 +22,6 @@ import java.io.OutputStream;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLEventWriter;
@@ -19,6 +34,7 @@ import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlSaxHandler; import org.apache.xmlbeans.XmlSaxHandler;
import org.apache.xmlbeans.XmlValidationError; import org.apache.xmlbeans.XmlValidationError;
import org.apache.xmlbeans.XMLStreamValidationException;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
@@ -30,24 +46,33 @@ import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.LexicalHandler;
import org.springframework.oxm.AbstractMarshaller;
import org.springframework.oxm.Marshaller; import org.springframework.oxm.Marshaller;
import org.springframework.oxm.ValidationFailureException;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.UncategorizedMappingException;
import org.springframework.oxm.support.AbstractMarshaller;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
/** /**
* Implementation of the {@link Marshaller} interface for XMLBeans. Further options can be set by setting the * Implementation of the {@link Marshaller} interface for Apache XMLBeans.
* <code>xmlOptions</code> property. The {@link XmlOptionsFactoryBean} is provided to easily wire up {@link XmlOptions} *
* instances. <p/> Unmarshalled objects can be validated by setting the <code>validating</code> property, or by calling * <p>Options can be set by setting the <code>xmlOptions</code> property.
* the {@link #validate(XmlObject)} method directly. Invalid objects will result in an {@link * The {@link XmlOptionsFactoryBean} is provided to easily set up an {@link XmlOptions} instance.
* XmlBeansValidationFailureException}. <p/> <strong>Note</strong> that due to the nature of XMLBeans, this marshaller *
* requires all passed objects to be of type {@link XmlObject}. * <p>Unmarshalled objects can be validated by setting the <code>validating</code> property,
* or by calling the {@link #validate(XmlObject)} method directly. Invalid objects will
* result in an {@link XmlBeansValidationFailureException}.
*
* <p><b>NOTE:</b> Due to the nature of XMLBeans, this marshaller requires
* all passed objects to be of type {@link XmlObject}.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @see #setXmlOptions(org.apache.xmlbeans.XmlOptions)
* @see XmlOptionsFactoryBean
* @see #setValidating(boolean)
* @since 3.0 * @since 3.0
* @see #setValidating
* @see #setXmlOptions
* @see XmlOptionsFactoryBean
*/ */
public class XmlBeansMarshaller extends AbstractMarshaller { public class XmlBeansMarshaller extends AbstractMarshaller {
@@ -55,16 +80,9 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
private boolean validating = false; private boolean validating = false;
/**
* Returns the <code>XmlOptions</code>.
*/
public XmlOptions getXmlOptions() {
return xmlOptions;
}
/** /**
* Sets the <code>XmlOptions</code>. * Set the <code>XmlOptions</code>.
*
* @see XmlOptionsFactoryBean * @see XmlOptionsFactoryBean
*/ */
public void setXmlOptions(XmlOptions xmlOptions) { public void setXmlOptions(XmlOptions xmlOptions) {
@@ -72,21 +90,30 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
} }
/** /**
* Returns whether this marshaller should validate in- and outgoing documents. * Return the <code>XmlOptions</code>.
*/ */
public boolean isValidating() { public XmlOptions getXmlOptions() {
return validating; return this.xmlOptions;
} }
/** /**
* Sets whether this marshaller should validate in- and outgoing documents. Default is <code>false</code>. * Set whether this marshaller should validate in- and outgoing documents.
* Default is <code>false</code>.
*/ */
public void setValidating(boolean validating) { public void setValidating(boolean validating) {
this.validating = validating; this.validating = validating;
} }
/** /**
* Returns true if the given class is an implementation of {@link XmlObject}. * Return whether this marshaller should validate in- and outgoing documents.
*/
public boolean isValidating() {
return this.validating;
}
/**
* This implementation returns true if the given class is an implementation of {@link XmlObject}.
*/ */
public boolean supports(Class<?> clazz) { public boolean supports(Class<?> clazz) {
return XmlObject.class.isAssignableFrom(clazz); return XmlObject.class.isAssignableFrom(clazz);
@@ -107,6 +134,7 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
@Override @Override
protected final void marshalOutputStream(Object graph, OutputStream outputStream) protected final void marshalOutputStream(Object graph, OutputStream outputStream)
throws XmlMappingException, IOException { throws XmlMappingException, IOException {
((XmlObject) graph).save(outputStream, getXmlOptions()); ((XmlObject) graph).save(outputStream, getXmlOptions());
} }
@@ -225,30 +253,13 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
} }
} }
/**
* Converts the given XMLBeans exception to an appropriate exception from the <code>org.springframework.oxm</code>
* hierarchy. <p/> The default implementation delegates to <code>XmlBeansUtils</code>. Can be overridden in subclasses.
* <p/> A boolean flag is used to indicate whether this exception occurs during marshalling or unmarshalling, since
* XMLBeans itself does not make this distinction in its exception hierarchy.
*
* @param ex XMLBeans Exception that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
* @see XmlBeansUtils#convertXmlBeansException(Exception,boolean)
*/
public XmlMappingException convertXmlBeansException(Exception ex, boolean marshalling) {
return XmlBeansUtils.convertXmlBeansException(ex, marshalling);
}
/** /**
* Validates the given <code>XmlObject</code>. * Validate the given <code>XmlObject</code>.
*
* @param object the xml object to validate * @param object the xml object to validate
* @throws XmlBeansValidationFailureException * @throws XmlBeansValidationFailureException if the given object is not valid
* if the given object is not valid
*/ */
public void validate(XmlObject object) throws XmlBeansValidationFailureException { protected void validate(XmlObject object) throws ValidationFailureException {
if (isValidating() && object != null) { if (isValidating() && object != null) {
// create a temporary xmlOptions just for validation // create a temporary xmlOptions just for validation
XmlOptions validateOptions = getXmlOptions() != null ? getXmlOptions() : new XmlOptions(); XmlOptions validateOptions = getXmlOptions() != null ? getXmlOptions() : new XmlOptions();
@@ -256,15 +267,44 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
validateOptions.setErrorListener(errorsList); validateOptions.setErrorListener(errorsList);
if (!object.validate(validateOptions)) { if (!object.validate(validateOptions)) {
StringBuilder builder = new StringBuilder("Could not validate XmlObject :"); StringBuilder builder = new StringBuilder("Could not validate XmlObject :");
for (Iterator iterator = errorsList.iterator(); iterator.hasNext();) { for (Object anErrorsList : errorsList) {
XmlError xmlError = (XmlError) iterator.next(); XmlError xmlError = (XmlError) anErrorsList;
if (xmlError instanceof XmlValidationError) { if (xmlError instanceof XmlValidationError) {
builder.append(xmlError.toString()); builder.append(xmlError.toString());
} }
} }
XmlException ex = new XmlException(builder.toString(), null, errorsList); throw new ValidationFailureException("XMLBeans validation failure",
throw new XmlBeansValidationFailureException(ex); new XmlException(builder.toString(), null, errorsList));
} }
} }
} }
/**
* Convert the given XMLBeans exception to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy.
* <p>A boolean flag is used to indicate whether this exception occurs during marshalling or
* unmarshalling, since XMLBeans itself does not make this distinction in its exception hierarchy.
* @param ex XMLBeans Exception that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>),
* or unmarshalling (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
*/
protected XmlMappingException convertXmlBeansException(Exception ex, boolean marshalling) {
if (ex instanceof XMLStreamValidationException) {
return new ValidationFailureException("XmlBeans validation exception", ex);
}
else if (ex instanceof XmlException || ex instanceof SAXException) {
if (marshalling) {
return new MarshallingFailureException("XMLBeans marshalling exception", ex);
}
else {
return new UnmarshallingFailureException("XMLBeans unmarshalling exception", ex);
}
}
else {
// fallback
return new UncategorizedMappingException("Unknown XMLBeans exception", ex);
}
}
} }

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XmlException;
import org.xml.sax.SAXException;
import org.springframework.oxm.MarshallingFailureException;
/**
* XMLBeans-specific subclass of <code>MarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see XmlBeansUtils#convertXmlBeansException(Exception,boolean)
* @since 3.0
*/
public class XmlBeansMarshallingFailureException extends MarshallingFailureException {
public XmlBeansMarshallingFailureException(XmlException ex) {
super("XMLBeans marshalling exception: " + ex.getMessage(), ex);
}
public XmlBeansMarshallingFailureException(SAXException ex) {
super("XMLBeans marshalling exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xmlbeans;
import org.springframework.oxm.UncategorizedXmlMappingException;
/**
* XMLBeans-specific subclass of <code>UncategorizedXmlMappingException</code>, for XMLBeans exceptions that cannot be
* distinguished further.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class XmlBeansSystemException extends UncategorizedXmlMappingException {
public XmlBeansSystemException(Exception e) {
super(e.getMessage(), e);
}
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XmlException;
import org.xml.sax.SAXException;
import org.springframework.oxm.UnmarshallingFailureException;
/**
* XMLBeans-specific subclass of <code>UnmarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see XmlBeansUtils#convertXmlBeansException(Exception,boolean)
* @since 3.0
*/
public class XmlBeansUnmarshallingFailureException extends UnmarshallingFailureException {
public XmlBeansUnmarshallingFailureException(XmlException ex) {
super("XMLBeans unmarshalling exception: " + ex.getMessage(), ex);
}
public XmlBeansUnmarshallingFailureException(SAXException ex) {
super("XMLBeans unmarshalling exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,68 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XMLStreamValidationException;
import org.apache.xmlbeans.XmlException;
import org.xml.sax.SAXException;
import org.springframework.oxm.XmlMappingException;
/**
* Generic utility methods for working with XMLBeans. Mainly for internal use within the framework.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class XmlBeansUtils {
/**
* Converts the given XMLBeans exception to an appropriate exception from the <code>org.springframework.oxm</code>
* hierarchy. <p/> A boolean flag is used to indicate whether this exception occurs during marshalling or
* unmarshalling, since XMLBeans itself does not make this distinction in its exception hierarchy.
*
* @param ex XMLBeans Exception that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
*/
public static XmlMappingException convertXmlBeansException(Exception ex, boolean marshalling) {
if (ex instanceof XMLStreamValidationException) {
return new XmlBeansValidationFailureException((XMLStreamValidationException) ex);
}
else if (ex instanceof XmlException) {
XmlException xmlException = (XmlException) ex;
if (marshalling) {
return new XmlBeansMarshallingFailureException(xmlException);
}
else {
return new XmlBeansUnmarshallingFailureException(xmlException);
}
}
else if (ex instanceof SAXException) {
SAXException saxException = (SAXException) ex;
if (marshalling) {
return new XmlBeansMarshallingFailureException(saxException);
}
else {
return new XmlBeansUnmarshallingFailureException(saxException);
}
}
// fallback
return new XmlBeansSystemException(ex);
}
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XMLStreamValidationException;
import org.apache.xmlbeans.XmlException;
import org.springframework.oxm.ValidationFailureException;
/**
* XMLBeans-specific subclass of <code>ValidationFailureException</code>.
*
* @author Arjen Poutsma
* @see org.springframework.oxm.xmlbeans.XmlBeansUtils#convertXmlBeansException
* @since 3.0
*/
public class XmlBeansValidationFailureException extends ValidationFailureException {
public XmlBeansValidationFailureException(XMLStreamValidationException ex) {
super("XmlBeans validation exception: " + ex.getMessage(), ex);
}
public XmlBeansValidationFailureException(XmlException ex) {
super("XmlBeans validation exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,64 +16,58 @@
package org.springframework.oxm.xmlbeans; package org.springframework.oxm.xmlbeans;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlOptions;
import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
/** /**
* Factory bean that configures an XMLBeans <code>XmlOptions</code> object and provides it as a bean reference. <p/> * {@link FactoryBean} that configures an XMLBeans <code>XmlOptions</code> object
* Typical usage will be to set XMLBeans options on this bean, and refer to it in the <code>XmlBeansMarshaller</code>. * and provides it as a bean reference.
*
* <p>Typical usage will be to set XMLBeans options on this bean, and refer to it
* in the {@link XmlBeansMarshaller}.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0
* @see XmlOptions * @see XmlOptions
* @see #setOptions(java.util.Map) * @see #setOptions(java.util.Map)
* @see XmlBeansMarshaller#setXmlOptions(org.apache.xmlbeans.XmlOptions) * @see XmlBeansMarshaller#setXmlOptions(XmlOptions)
* @since 3.0
*/ */
public class XmlOptionsFactoryBean implements FactoryBean, InitializingBean { public class XmlOptionsFactoryBean implements FactoryBean<XmlOptions> {
private XmlOptions xmlOptions; private XmlOptions xmlOptions;
private Map options;
/** Returns the singleton <code>XmlOptions</code>. */
public Object getObject() throws Exception {
return xmlOptions;
}
/** Returns the class of <code>XmlOptions</code>. */
public Class getObjectType() {
return XmlOptions.class;
}
/** Returns <code>true</code>. */
public boolean isSingleton() {
return true;
}
/** /**
* Sets options on the underlying <code>XmlOptions</code> object. The keys of the supplied map should be one of the * Set options on the underlying <code>XmlOptions</code> object.
* string constants defined in <code>XmlOptions</code>, the values vary per option. * <p>The keys of the supplied map should be one of the String constants
* * defined in <code>XmlOptions</code>, the values vary per option.
* @see XmlOptions#put(Object,Object) * @see XmlOptions#put(Object,Object)
* @see XmlOptions#SAVE_PRETTY_PRINT * @see XmlOptions#SAVE_PRETTY_PRINT
* @see XmlOptions#LOAD_STRIP_COMMENTS * @see XmlOptions#LOAD_STRIP_COMMENTS
*/ */
public void setOptions(Map options) { public void setOptions(Map<String, ?> optionsMap) {
this.options = options; this.xmlOptions = new XmlOptions();
} if (optionsMap != null) {
for (String option : optionsMap.keySet()) {
public void afterPropertiesSet() throws Exception { this.xmlOptions.put(option, optionsMap.get(option));
xmlOptions = new XmlOptions();
if (options != null) {
for (Iterator iterator = options.keySet().iterator(); iterator.hasNext();) {
Object option = iterator.next();
xmlOptions.put(option, options.get(option));
} }
} }
} }
public XmlOptions getObject() {
return this.xmlOptions;
}
public Class<? extends XmlOptions> getObjectType() {
return XmlOptions.class;
}
public boolean isSingleton() {
return true;
}
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLEventWriter;
@@ -32,12 +31,14 @@ import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.XMLStreamWriter;
import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterMatcher; import com.thoughtworks.xstream.converters.ConverterMatcher;
import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.xml.CompactWriter; import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.DomReader; import com.thoughtworks.xstream.io.xml.DomReader;
import com.thoughtworks.xstream.io.xml.DomWriter; import com.thoughtworks.xstream.io.xml.DomWriter;
@@ -47,6 +48,7 @@ import com.thoughtworks.xstream.io.xml.StaxReader;
import com.thoughtworks.xstream.io.xml.StaxWriter; import com.thoughtworks.xstream.io.xml.StaxWriter;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer; import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppReader; import com.thoughtworks.xstream.io.xml.XppReader;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
@@ -55,100 +57,83 @@ import org.xml.sax.InputSource;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.LexicalHandler;
import org.springframework.beans.propertyeditors.ClassEditor; import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.AbstractMarshaller; import org.springframework.oxm.UncategorizedMappingException;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.support.AbstractMarshaller;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
/** /**
* Implementation of the <code>Marshaller</code> interface for XStream. By default, XStream does not require any further * Implementation of the <code>Marshaller</code> interface for XStream.
* configuration, though class aliases can be used to have more control over the behavior of XStream. <p/> Due to *
* XStream's API, it is required to set the encoding used for writing to outputstreams. It defaults to * <p>By default, XStream does not require any further configuration,
* <code>UTF-8</code>. <p/> <b>Note</b> that XStream is an XML serialization library, not a data binding library. * though class aliases can be used to have more control over the behavior of XStream.
* Therefore, it has limited namespace support. As such, it is rather unsuitable for usage within Web services. *
* <p>Due to XStream's API, it is required to set the encoding used for writing to OutputStreams.
* It defaults to <code>UTF-8</code>.
*
* <p><b>NOTE:</b> XStream is an XML serialization library, not a data binding library.
* Therefore, it has limited namespace support. As such, it is rather unsuitable for
* usage within Web services.
* *
* @author Peter Meijer * @author Peter Meijer
* @author Arjen Poutsma * @author Arjen Poutsma
* @see #setEncoding(String)
* @see #DEFAULT_ENCODING
* @see #setAliases(Map)
* @see #setConverters(ConverterMatcher[])
* @since 3.0 * @since 3.0
* @see #setAliases
* @see #setConverters
* @see #setEncoding
*/ */
public class XStreamMarshaller extends AbstractMarshaller { public class XStreamMarshaller extends AbstractMarshaller {
/** The default encoding used for stream access. */ /**
* The default encoding used for stream access: UTF-8.
*/
public static final String DEFAULT_ENCODING = "UTF-8"; public static final String DEFAULT_ENCODING = "UTF-8";
private XStream xstream = new XStream();
private String encoding; private final XStream xstream = new XStream();
private HierarchicalStreamDriver streamDriver;
private String encoding = DEFAULT_ENCODING;
private Class[] supportedClasses; private Class[] supportedClasses;
/** Specialized driver to be used with stream readers and writers */
private HierarchicalStreamDriver streamDriver;
/** /**
* Returns the encoding to be used for stream access. If this property is not set, the default encoding is used. * Returns the XStream instance used by this marshaller.
*
* @see #DEFAULT_ENCODING
*/ */
public String getEncoding() { public final XStream getXStream() {
return encoding != null ? encoding : DEFAULT_ENCODING; return this.xstream;
} }
/** /**
* Sets the encoding to be used for stream access. If this property is not set, the default encoding is used. * Set the XStream mode.
*
* @see #DEFAULT_ENCODING
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/** Returns the XStream instance used by this marshaller. */
public XStream getXStream() {
return xstream;
}
/**
* Sets the XStream mode.
*
* @see XStream#XPATH_REFERENCES * @see XStream#XPATH_REFERENCES
* @see XStream#ID_REFERENCES * @see XStream#ID_REFERENCES
* @see XStream#NO_REFERENCES * @see XStream#NO_REFERENCES
*/ */
public void setMode(int mode) { public void setMode(int mode) {
getXStream().setMode(mode); this.xstream.setMode(mode);
} }
/** /**
* Sets the classes supported by this marshaller. If this property is empty (the default), all classes are supported. * Set the <code>Converters</code> or <code>SingleValueConverters</code> to be registered
* * with the <code>XStream</code> instance.
* @see #supports(Class)
*/
public void setSupportedClasses(Class[] supportedClasses) {
this.supportedClasses = supportedClasses;
}
/**
* Sets the <code>Converters</code> or <code>SingleValueConverters</code> to be registered with the
* <code>XStream</code> instance.
*
* @see Converter * @see Converter
* @see SingleValueConverter * @see SingleValueConverter
*/ */
public void setConverters(ConverterMatcher[] converters) { public void setConverters(ConverterMatcher[] converters) {
for (int i = 0; i < converters.length; i++) { for (int i = 0; i < converters.length; i++) {
if (converters[i] instanceof Converter) { if (converters[i] instanceof Converter) {
getXStream().registerConverter((Converter) converters[i], i); this.xstream.registerConverter((Converter) converters[i], i);
} }
else if (converters[i] instanceof SingleValueConverter) { else if (converters[i] instanceof SingleValueConverter) {
getXStream().registerConverter((SingleValueConverter) converters[i], i); this.xstream.registerConverter((SingleValueConverter) converters[i], i);
} }
else { else {
throw new IllegalArgumentException("Invalid ConverterMatcher [" + converters[i] + "]"); throw new IllegalArgumentException("Invalid ConverterMatcher [" + converters[i] + "]");
@@ -156,68 +141,48 @@ public class XStreamMarshaller extends AbstractMarshaller {
} }
} }
/** Sets the XStream hierarchical stream driver to be used with stream readers and writers */
public void setStreamDriver(HierarchicalStreamDriver streamDriver) {
this.streamDriver = streamDriver;
}
/** /**
* Set a alias/type map, consisting of string aliases mapped to <code>Class</code> instances (or Strings to be * Set an alias/type map, consisting of string aliases mapped to <code>Class</code> instances.
* converted to <code>Class</code> instances).
*
* @see org.springframework.beans.propertyeditors.ClassEditor
*/ */
public void setAliases(Map aliases) { public void setAliases(Map<String, Class> aliases) {
for (Iterator iterator = aliases.entrySet().iterator(); iterator.hasNext();) { for (Map.Entry<String, Class> entry : aliases.entrySet()) {
Map.Entry entry = (Map.Entry) iterator.next(); this.xstream.alias(entry.getKey(), entry.getValue());
// Check whether we need to convert from String to Class.
Class type;
if (entry.getValue() instanceof Class) {
type = (Class) entry.getValue();
}
else {
ClassEditor editor = new ClassEditor();
editor.setAsText(String.valueOf(entry.getValue()));
type = (Class) editor.getValue();
}
addAlias((String) entry.getKey(), type);
} }
} }
/** /**
* Adds an alias for the given type. * Add an alias for the given type.
*
* @param name alias to be used for the type * @param name alias to be used for the type
* @param type the type to be aliased * @param type the type to be aliased
*/ */
public void addAlias(String name, Class type) { public void addAlias(String name, Class type) {
getXStream().alias(name, type); this.xstream.alias(name, type);
} }
/** /**
* Sets types to use XML attributes for. * Set types to use XML attributes for.
*
* @see XStream#useAttributeFor(Class) * @see XStream#useAttributeFor(Class)
*/ */
public void setUseAttributeForTypes(Class[] types) { public void setUseAttributeForTypes(Class[] types) {
for (Class type : types) { for (Class type : types) {
getXStream().useAttributeFor(type); this.xstream.useAttributeFor(type);
} }
} }
/** /**
* Sets the types to use XML attributes for. The given map can contain either <code>&lt;String, Class&gt;</code> pairs, * Set the types to use XML attributes for. The given map can contain
* in which case {@link XStream#useAttributeFor(String,Class)} is called, or <code>&lt;Class, String&gt;</code> pairs, * either <code>&lt;String, Class&gt;</code> pairs, in which case
* which results in {@link XStream#useAttributeFor(Class,String)}. * {@link XStream#useAttributeFor(String, Class)} is called,
* or <code>&lt;Class, String&gt;</code> pairs, which results in
* {@link XStream#useAttributeFor(Class, String)} calls.
*/ */
public void setUseAttributeFor(Map attributes) { public void setUseAttributeFor(Map<?, ?> attributes) {
for (Iterator iterator = attributes.entrySet().iterator(); iterator.hasNext();) { for (Map.Entry<?, ?> entry : attributes.entrySet()) {
Map.Entry entry = (Map.Entry) iterator.next();
if (entry.getKey() instanceof String && entry.getValue() instanceof Class) { if (entry.getKey() instanceof String && entry.getValue() instanceof Class) {
getXStream().useAttributeFor((String) entry.getKey(), (Class) entry.getValue()); this.xstream.useAttributeFor((String) entry.getKey(), (Class) entry.getValue());
} }
else if (entry.getKey() instanceof Class && entry.getValue() instanceof String) { else if (entry.getKey() instanceof Class && entry.getValue() instanceof String) {
getXStream().useAttributeFor((Class) entry.getKey(), (String) entry.getValue()); this.xstream.useAttributeFor((Class) entry.getKey(), (String) entry.getValue());
} }
else { else {
throw new IllegalArgumentException("Invalid attribute key and value pair. " + throw new IllegalArgumentException("Invalid attribute key and value pair. " +
@@ -227,102 +192,97 @@ public class XStreamMarshaller extends AbstractMarshaller {
} }
/** /**
* Adds an implicit Collection for the given type. * Set a implicit colletion/type map, consisting of implicit collection String keys
* * mapped to <code>Class</code> values.
* @see XStream#addImplicitCollection(Class, String) * @see XStream#addImplicitCollection(Class, String)
*/ */
public void addImplicitCollection(String name, Class type) { public void setImplicitCollection(Map<String, Class> implicitCollection) {
getXStream().addImplicitCollection(type, name); for (Map.Entry<String, Class> entry : implicitCollection.entrySet()) {
} this.xstream.addImplicitCollection(entry.getValue(), entry.getKey());
/**
* Set a implicit colletion/type map, consisting of string implicit collection mapped to <code>Class</code> instances
* (or Strings to be converted to <code>Class</code> instances).
*
* @see XStream#addImplicitCollection(Class, String)
*/
public void setImplicitCollection(Map implicitCollection) {
for (Iterator iterator = implicitCollection.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
// Check whether we need to convert from String to Class.
Class type;
if (entry.getValue() instanceof Class) {
type = (Class) entry.getValue();
}
else {
ClassEditor editor = new ClassEditor();
editor.setAsText(String.valueOf(entry.getValue()));
type = (Class) editor.getValue();
}
addImplicitCollection((String) entry.getKey(), type);
} }
} }
/** /**
* Adds an omitted field for the given type. * Add an implicit Collection for the given type.
* * @see XStream#addImplicitCollection(Class, String)
* @param type the type to be containing the field */
public void addImplicitCollection(String name, Class type) {
this.xstream.addImplicitCollection(type, name);
}
/**
* Specify omitted fields, as a Map consisting of <code>Class</code> instances
* mapped to comma separated field names.
* @see XStream#omitField(Class, String)
*/
public void setOmittedFields(Map<Class, String> omittedFields) {
for (Map.Entry<Class, String> entry : omittedFields.entrySet()) {
String[] fields = StringUtils.commaDelimitedListToStringArray(entry.getValue());
for (String field : fields) {
this.xstream.omitField(entry.getKey(), field);
}
}
}
/**
* Add an omitted field for the given type.
* @param type the type to be containing the field
* @param fieldName field to omitt * @param fieldName field to omitt
* @see XStream#omitField(Class, String) * @see XStream#omitField(Class, String)
*/ */
public void addOmittedField(Class type, String fieldName) { public void addOmittedField(Class type, String fieldName) {
getXStream().omitField(type, fieldName); this.xstream.omitField(type, fieldName);
} }
/** /**
* Sets a ommited field map, consisting of <code>Class</code> instances (or Strings to be converted to * Set the classes for which mappings will be read from class-level JDK 1.5+ annotation metadata.
* <code>Class</code> instances) mapped to comma separated field names. * @see com.thoughtworks.xstream.XStream#processAnnotations(Class)
*
* @see XStream#omitField(Class, String)
*/
public void setOmittedFields(Map omittedFields) {
for (Iterator iterator = omittedFields.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
// Check whether we need to convert from String to Class.
Class type;
if (entry.getKey() instanceof Class) {
type = (Class) entry.getKey();
}
else {
ClassEditor editor = new ClassEditor();
editor.setAsText(String.valueOf(entry.getKey()));
type = (Class) editor.getValue();
}
// add each omitted field for the current type
String fieldsString = (String) entry.getValue();
String[] fields = StringUtils.commaDelimitedListToStringArray(fieldsString);
for (String field : fields) {
addOmittedField(type, field);
}
}
}
/**
* Sets the classes, for which mappings will be read from class-level JDK 1.5+ annotation metadata.
*
* @see com.thoughtworks.xstream.annotations.Annotations#configureAliases(com.thoughtworks.xstream.XStream, Class[])
*/ */
public void setAnnotatedClass(Class<?> annotatedClass) { public void setAnnotatedClass(Class<?> annotatedClass) {
Assert.notNull(annotatedClass, "'annotatedClass' must not be null"); Assert.notNull(annotatedClass, "'annotatedClass' must not be null");
getXStream().processAnnotations(annotatedClass); this.xstream.processAnnotations(annotatedClass);
} }
/** /**
* Sets annotated classes, for which aliases will be read from class-level JDK 1.5+ annotation metadata. * Set annotated classes for which aliases will be read from class-level JDK 1.5+ annotation metadata.
* * @see com.thoughtworks.xstream.XStream#processAnnotations(Class[])
* @see com.thoughtworks.xstream.annotations.Annotations#configureAliases(com.thoughtworks.xstream.XStream, Class[])
*/ */
public void setAnnotatedClasses(Class<?>[] annotatedClasses) { public void setAnnotatedClasses(Class<?>[] annotatedClasses) {
Assert.notEmpty(annotatedClasses, "'annotatedClasses' must not be empty"); Assert.notEmpty(annotatedClasses, "'annotatedClasses' must not be empty");
getXStream().processAnnotations(annotatedClasses); this.xstream.processAnnotations(annotatedClasses);
} }
/**
* Set the XStream hierarchical stream driver to be used with stream readers and writers.
*/
public void setStreamDriver(HierarchicalStreamDriver streamDriver) {
this.streamDriver = streamDriver;
}
/**
* Set the encoding to be used for stream access.
* @see #DEFAULT_ENCODING
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Set the classes supported by this marshaller.
* <p>If this property is empty (the default), all classes are supported.
* @see #supports(Class)
*/
public void setSupportedClasses(Class[] supportedClasses) {
this.supportedClasses = supportedClasses;
}
public boolean supports(Class clazz) { public boolean supports(Class clazz) {
if (ObjectUtils.isEmpty(supportedClasses)) { if (ObjectUtils.isEmpty(this.supportedClasses)) {
return true; return true;
} }
else { else {
for (Class supportedClass : supportedClasses) { for (Class supportedClass : this.supportedClasses) {
if (supportedClass.isAssignableFrom(clazz)) { if (supportedClass.isAssignableFrom(clazz)) {
return true; return true;
} }
@@ -331,36 +291,8 @@ public class XStreamMarshaller extends AbstractMarshaller {
} }
} }
/**
* Convert the given XStream exception to an appropriate exception from the <code>org.springframework.oxm</code>
* hierarchy. <p/> The default implementation delegates to <code>XStreamUtils</code>. Can be overridden in subclasses.
*
* @param ex exception that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code> instance
* @see XStreamUtils#convertXStreamException(Exception,boolean)
*/
public XmlMappingException convertXStreamException(Exception ex, boolean marshalling) {
return XStreamUtils.convertXStreamException(ex, marshalling);
}
//
// Marshalling // Marshalling
//
/**
* Marshals the given graph to the given XStream HierarchicalStreamWriter. Converts exceptions using
* <code>convertXStreamException</code>.
*/
private void marshal(Object graph, HierarchicalStreamWriter streamWriter) {
try {
getXStream().marshal(graph, streamWriter);
}
catch (Exception ex) {
throw convertXStreamException(ex, true);
}
}
@Override @Override
protected void marshalDomNode(Object graph, Node node) throws XmlMappingException { protected void marshalDomNode(Object graph, Node node) throws XmlMappingException {
@@ -394,14 +326,14 @@ public class XStreamMarshaller extends AbstractMarshaller {
} }
@Override @Override
protected void marshalOutputStream(Object graph, OutputStream outputStream) protected void marshalOutputStream(Object graph, OutputStream outputStream) throws XmlMappingException, IOException {
throws XmlMappingException, IOException { marshalWriter(graph, new OutputStreamWriter(outputStream, this.encoding));
marshalWriter(graph, new OutputStreamWriter(outputStream, getEncoding()));
} }
@Override @Override
protected void marshalSaxHandlers(Object graph, ContentHandler contentHandler, LexicalHandler lexicalHandler) protected void marshalSaxHandlers(Object graph, ContentHandler contentHandler, LexicalHandler lexicalHandler)
throws XmlMappingException { throws XmlMappingException {
SaxWriter saxWriter = new SaxWriter(); SaxWriter saxWriter = new SaxWriter();
saxWriter.setContentHandler(contentHandler); saxWriter.setContentHandler(contentHandler);
marshal(graph, saxWriter); marshal(graph, saxWriter);
@@ -417,19 +349,22 @@ public class XStreamMarshaller extends AbstractMarshaller {
} }
} }
// /**
// Unmarshalling * Marshals the given graph to the given XStream HierarchicalStreamWriter.
// * Converts exceptions using {@link #convertXStreamException}.
*/
private Object unmarshal(HierarchicalStreamReader streamReader) { private void marshal(Object graph, HierarchicalStreamWriter streamWriter) {
try { try {
return getXStream().unmarshal(streamReader); this.xstream.marshal(graph, streamWriter);
} }
catch (Exception ex) { catch (Exception ex) {
throw convertXStreamException(ex, false); throw convertXStreamException(ex, true);
} }
} }
// Unmarshalling
@Override @Override
protected Object unmarshalDomNode(Node node) throws XmlMappingException { protected Object unmarshalDomNode(Node node) throws XmlMappingException {
HierarchicalStreamReader streamReader; HierarchicalStreamReader streamReader;
@@ -463,7 +398,7 @@ public class XStreamMarshaller extends AbstractMarshaller {
@Override @Override
protected Object unmarshalInputStream(InputStream inputStream) throws XmlMappingException, IOException { protected Object unmarshalInputStream(InputStream inputStream) throws XmlMappingException, IOException {
return unmarshalReader(new InputStreamReader(inputStream, getEncoding())); return unmarshalReader(new InputStreamReader(inputStream, this.encoding));
} }
@Override @Override
@@ -479,8 +414,45 @@ public class XStreamMarshaller extends AbstractMarshaller {
@Override @Override
protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
throws XmlMappingException, IOException { throws XmlMappingException, IOException {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"XStreamMarshaller does not support unmarshalling using SAX XMLReaders"); "XStreamMarshaller does not support unmarshalling using SAX XMLReaders");
} }
private Object unmarshal(HierarchicalStreamReader streamReader) {
try {
return this.xstream.unmarshal(streamReader);
}
catch (Exception ex) {
throw convertXStreamException(ex, false);
}
}
/**
* Convert the given XStream exception to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy.
* <p>A boolean flag is used to indicate whether this exception occurs during marshalling or
* unmarshalling, since XStream itself does not make this distinction in its exception hierarchy.
* @param ex XStream exception that occured
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>),
* or unmarshalling (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
*/
protected XmlMappingException convertXStreamException(Exception ex, boolean marshalling) {
if (ex instanceof StreamException || ex instanceof CannotResolveClassException ||
ex instanceof ConversionException) {
if (marshalling) {
return new MarshallingFailureException("XStream marshalling exception", ex);
}
else {
return new UnmarshallingFailureException("XStream unmarshalling exception", ex);
}
}
else {
// fallback
return new UncategorizedMappingException("Unknown XStream exception", ex);
}
}
} }

View File

@@ -1,50 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xstream;
import com.thoughtworks.xstream.alias.CannotResolveClassException;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.io.StreamException;
import org.springframework.oxm.MarshallingFailureException;
/**
* XStream-specific subclass of <code>MarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class XStreamMarshallingFailureException extends MarshallingFailureException {
public XStreamMarshallingFailureException(String msg) {
super(msg);
}
public XStreamMarshallingFailureException(StreamException ex) {
super("XStream marshalling exception: " + ex.getMessage(), ex);
}
public XStreamMarshallingFailureException(CannotResolveClassException ex) {
super("XStream resolving exception: " + ex.getMessage(), ex);
}
public XStreamMarshallingFailureException(ConversionException ex) {
super("XStream conversion exception: " + ex.getMessage(), ex);
}
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xstream;
import org.springframework.oxm.UncategorizedXmlMappingException;
/**
* XStream-specific subclass of <code>UncategorizedXmlMappingException</code>, for XStream exceptions that cannot be
* distinguished further.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class XStreamSystemException extends UncategorizedXmlMappingException {
public XStreamSystemException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xstream;
import javax.xml.stream.XMLStreamException;
import com.thoughtworks.xstream.alias.CannotResolveClassException;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.io.StreamException;
import org.springframework.oxm.UnmarshallingFailureException;
/**
* XStream-specific subclass of <code>UnmarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class XStreamUnmarshallingFailureException extends UnmarshallingFailureException {
public XStreamUnmarshallingFailureException(StreamException ex) {
super("XStream unmarshalling exception: " + ex.getMessage(), ex);
}
public XStreamUnmarshallingFailureException(CannotResolveClassException ex) {
super("XStream resolving exception: " + ex.getMessage(), ex);
}
public XStreamUnmarshallingFailureException(ConversionException ex) {
super("XStream conversion exception: " + ex.getMessage(), ex);
}
public XStreamUnmarshallingFailureException(String msg) {
super(msg);
}
public XStreamUnmarshallingFailureException(String msg, XMLStreamException ex) {
super(msg, ex);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,57 +16,48 @@
package org.springframework.oxm.xstream; package org.springframework.oxm.xstream;
import com.thoughtworks.xstream.alias.CannotResolveClassException;
import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.io.StreamException; import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.UncategorizedMappingException;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
/** /**
* Generic utility methods for working with XStream. Mainly for internal use within the framework. * Generic utility methods for working with XStream. Mainly for internal use within the framework.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0 * @since 3.0
*/ */
public abstract class XStreamUtils { abstract class XStreamUtils {
/** /**
* Converts the given XStream exception to an appropriate exception from the <code>org.springframework.oxm</code> * Convert the given XStream exception to an appropriate exception from the
* hierarchy. <p/> A boolean flag is used to indicate whether this exception occurs during marshalling or * <code>org.springframework.oxm</code> hierarchy.
* <p>A boolean flag is used to indicate whether this exception occurs during marshalling or
* unmarshalling, since XStream itself does not make this distinction in its exception hierarchy. * unmarshalling, since XStream itself does not make this distinction in its exception hierarchy.
* * @param ex XStream exception that occured
* @param ex XStream exception that occured * @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>),
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling * or unmarshalling (<code>false</code>)
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code> * @return the corresponding <code>XmlMappingException</code>
*/ */
public static XmlMappingException convertXStreamException(Exception ex, boolean marshalling) { public static XmlMappingException convertXStreamException(Exception ex, boolean marshalling) {
if (ex instanceof StreamException) { if (ex instanceof StreamException || ex instanceof CannotResolveClassException ||
ex instanceof ConversionException) {
if (marshalling) { if (marshalling) {
return new XStreamMarshallingFailureException((StreamException) ex); return new MarshallingFailureException("XStream marshalling exception", ex);
} }
else { else {
return new XStreamUnmarshallingFailureException((StreamException) ex); return new UnmarshallingFailureException("XStream unmarshalling exception", ex);
} }
} }
else if (ex instanceof CannotResolveClassException) { else {
if (marshalling) { // fallback
return new XStreamMarshallingFailureException((CannotResolveClassException) ex); return new UncategorizedMappingException("Unknown XStream exception", ex);
}
else {
return new XStreamUnmarshallingFailureException((CannotResolveClassException) ex);
}
} }
else if (ex instanceof ConversionException) {
if (marshalling) {
return new XStreamMarshallingFailureException((ConversionException) ex);
}
else {
return new XStreamUnmarshallingFailureException((ConversionException) ex);
}
}
// fallback
return new XStreamSystemException("Unknown XStream exception: " + ex.getMessage(), ex);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -38,7 +39,10 @@ import org.w3c.dom.Text;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
public abstract class AbstractMarshallerTestCase { /**
* @author Arjen Poutsma
*/
public abstract class AbstractMarshallerTests {
protected Marshaller marshaller; protected Marshaller marshaller;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm; package org.springframework.oxm;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -41,7 +42,10 @@ import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
public abstract class AbstractUnmarshallerTestCase { /**
* @author Arjen Poutsma
*/
public abstract class AbstractUnmarshallerTests {
protected Unmarshaller unmarshaller; protected Unmarshaller unmarshaller;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.castor; package org.springframework.oxm.castor;
import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXResult;
@@ -24,10 +25,13 @@ import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.AbstractMarshallerTestCase; import org.springframework.oxm.AbstractMarshallerTests;
import org.springframework.oxm.Marshaller; import org.springframework.oxm.Marshaller;
public class CastorMarshallerTest extends AbstractMarshallerTestCase { /**
* @author Arjen Poutsma
*/
public class CastorMarshallerTests extends AbstractMarshallerTests {
@Override @Override
protected Marshaller createMarshaller() throws Exception { protected Marshaller createMarshaller() throws Exception {
@@ -77,5 +81,4 @@ public class CastorMarshallerTest extends AbstractMarshallerTestCase {
assertTrue("CastorMarshaller does not support Flight", marshaller.supports(Flight.class)); assertTrue("CastorMarshaller does not support Flight", marshaller.supports(Flight.class));
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.castor; package org.springframework.oxm.castor;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -24,10 +25,13 @@ import static org.junit.Assert.assertNotNull;
import org.junit.Test; import org.junit.Test;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.AbstractUnmarshallerTestCase; import org.springframework.oxm.AbstractUnmarshallerTests;
import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.Unmarshaller;
public class CastorUnmarshallerTest extends AbstractUnmarshallerTestCase { /**
* @author Arjen Poutsma
*/
public class CastorUnmarshallerTests extends AbstractUnmarshallerTests {
@Override @Override
protected void testFlights(Object o) { protected void testFlights(Object o) {

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.castor;
import junit.framework.TestCase;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import org.exolab.castor.xml.XMLException;
public class CastorUtilsTest extends TestCase {
public void testConvertMarshalException() {
assertTrue("Invalid exception conversion", CastorUtils
.convertXmlException(new MarshalException(""), true) instanceof CastorMarshallingFailureException);
assertTrue("Invalid exception conversion", CastorUtils
.convertXmlException(new MarshalException(""), false) instanceof CastorUnmarshallingFailureException);
}
public void testConvertValidationException() {
assertTrue("Invalid exception conversion", CastorUtils
.convertXmlException(new ValidationException(""), false) instanceof CastorValidationFailureException);
}
public void testConvertXMLException() {
assertTrue("Invalid exception conversion",
CastorUtils.convertXmlException(new XMLException(""), false) instanceof CastorSystemException);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -21,12 +21,13 @@ import java.lang.reflect.Method;
import java.util.Collections; import java.util.Collections;
import javax.activation.DataHandler; import javax.activation.DataHandler;
import javax.activation.FileDataSource; import javax.activation.FileDataSource;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Result; import javax.xml.transform.Result;
import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;
import static org.easymock.EasyMock.*; import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.*;
import org.junit.Test; import org.junit.Test;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
@@ -34,13 +35,13 @@ import org.xml.sax.Locator;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.oxm.AbstractMarshallerTestCase; import org.springframework.oxm.AbstractMarshallerTests;
import org.springframework.oxm.Marshaller; import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.mime.MimeContainer; import org.springframework.oxm.mime.MimeContainer;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
public class Jaxb2MarshallerTest extends AbstractMarshallerTestCase { public class Jaxb2MarshallerTests extends AbstractMarshallerTests {
private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb"; private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb";
@@ -106,7 +107,7 @@ public class Jaxb2MarshallerTest extends AbstractMarshallerTestCase {
marshaller.afterPropertiesSet(); marshaller.afterPropertiesSet();
} }
@Test(expected = XmlMappingException.class) @Test(expected = JAXBException.class)
public void testInvalidContextPath() throws Exception { public void testInvalidContextPath() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("ab"); marshaller.setContextPath("ab");

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,12 +31,12 @@ import org.junit.Test;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.oxm.AbstractUnmarshallerTestCase; import org.springframework.oxm.AbstractUnmarshallerTests;
import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.mime.MimeContainer; import org.springframework.oxm.mime.MimeContainer;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
public class Jaxb2UnmarshallerTest extends AbstractUnmarshallerTestCase { public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests {
private static final String INPUT_STRING = "<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" + private static final String INPUT_STRING = "<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" +
"<tns:flight><tns:number>42</tns:number></tns:flight></tns:flights>"; "<tns:flight><tns:number>42</tns:number></tns:flight></tns:flights>";

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,10 +25,10 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
import org.springframework.oxm.AbstractMarshallerTestCase; import org.springframework.oxm.AbstractMarshallerTests;
import org.springframework.oxm.Marshaller; import org.springframework.oxm.Marshaller;
public class JibxMarshallerTest extends AbstractMarshallerTestCase { public class JibxMarshallerTests extends AbstractMarshallerTests {
@Override @Override
protected Marshaller createMarshaller() throws Exception { protected Marshaller createMarshaller() throws Exception {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,16 +13,20 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.jibx; package org.springframework.oxm.jibx;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import org.junit.Ignore; import org.junit.Ignore;
import org.springframework.oxm.AbstractUnmarshallerTestCase; import org.springframework.oxm.AbstractUnmarshallerTests;
import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.Unmarshaller;
public class JibxUnmarshallerTest extends AbstractUnmarshallerTestCase { /**
* @author Arjen Poutsma
*/
public class JibxUnmarshallerTests extends AbstractUnmarshallerTests {
@Override @Override
protected Unmarshaller createUnmarshaller() throws Exception { protected Unmarshaller createUnmarshaller() throws Exception {
@@ -52,4 +56,5 @@ public class JibxUnmarshallerTest extends AbstractUnmarshallerTestCase {
public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception { public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception {
// JiBX does not support reading XML fragments, hence the override here // JiBX does not support reading XML fragments, hence the override here
} }
} }

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.jibx;
import junit.framework.TestCase;
import org.jibx.runtime.JiBXException;
import org.jibx.runtime.ValidationException;
public class JibxUtilsTest extends TestCase {
public void testConvertMarshallingException() throws Exception {
assertTrue("Invalid exception conversion",
JibxUtils.convertJibxException(new JiBXException(""), true) instanceof JibxMarshallingFailureException);
}
public void testConvertUnmarshallingException() throws Exception {
assertTrue("Invalid exception conversion", JibxUtils
.convertJibxException(new JiBXException(""), false) instanceof JibxUnmarshallingFailureException);
}
public void testConvertValidationException() throws Exception {
assertTrue("Invalid exception conversion", JibxUtils
.convertJibxException(new ValidationException(""), true) instanceof JibxValidationFailureException);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.xmlbeans; package org.springframework.oxm.xmlbeans;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -23,12 +24,15 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
import org.springframework.oxm.AbstractMarshallerTestCase; import org.springframework.oxm.AbstractMarshallerTests;
import org.springframework.oxm.Marshaller; import org.springframework.oxm.Marshaller;
import org.springframework.samples.flight.FlightType; import org.springframework.samples.flight.FlightType;
import org.springframework.samples.flight.FlightsDocument; import org.springframework.samples.flight.FlightsDocument;
public class XmlBeansMarshallerTest extends AbstractMarshallerTestCase { /**
* @author Arjen Poutsma
*/
public class XmlBeansMarshallerTests extends AbstractMarshallerTests {
@Override @Override
protected Marshaller createMarshaller() throws Exception { protected Marshaller createMarshaller() throws Exception {
@@ -57,4 +61,5 @@ public class XmlBeansMarshallerTest extends AbstractMarshallerTestCase {
assertTrue("XmlBeansMarshaller does not support Flights", marshaller.supports(FlightsDocument.Flights.class)); assertTrue("XmlBeansMarshaller does not support Flights", marshaller.supports(FlightsDocument.Flights.class));
assertTrue("XmlBeansMarshaller does not support FlightType", marshaller.supports(FlightType.class)); assertTrue("XmlBeansMarshaller does not support FlightType", marshaller.supports(FlightType.class));
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2005 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.oxm.xmlbeans; package org.springframework.oxm.xmlbeans;
import java.io.StringReader; import java.io.StringReader;
@@ -22,18 +23,21 @@ import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import org.junit.Test; import org.junit.Test;
import org.springframework.oxm.AbstractUnmarshallerTestCase; import org.springframework.oxm.AbstractUnmarshallerTests;
import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.ValidationFailureException;
import org.springframework.samples.flight.FlightDocument; import org.springframework.samples.flight.FlightDocument;
import org.springframework.samples.flight.FlightType; import org.springframework.samples.flight.FlightType;
import org.springframework.samples.flight.FlightsDocument; import org.springframework.samples.flight.FlightsDocument;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
public class XmlBeansUnmarshallerTest extends AbstractUnmarshallerTestCase { /**
* @author Arjen Poutsma
*/
public class XmlBeansUnmarshallerTests extends AbstractUnmarshallerTests {
@Override @Override
protected Unmarshaller createUnmarshaller() throws Exception { protected Unmarshaller createUnmarshaller() throws Exception {
@@ -78,7 +82,7 @@ public class XmlBeansUnmarshallerTest extends AbstractUnmarshallerTestCase {
testFlight(flight); testFlight(flight);
} }
@Test(expected = XmlBeansValidationFailureException.class) @Test(expected = ValidationFailureException.class)
public void testValidate() throws Exception { public void testValidate() throws Exception {
((XmlBeansMarshaller) unmarshaller).setValidating(true); ((XmlBeansMarshaller) unmarshaller).setValidating(true);
String invalidInput = "<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" + String invalidInput = "<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" +

View File

@@ -1,53 +0,0 @@
/*
* Copyright 2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xmlbeans;
import junit.framework.TestCase;
import org.apache.xmlbeans.XMLStreamValidationException;
import org.apache.xmlbeans.XmlError;
import org.apache.xmlbeans.XmlException;
import org.xml.sax.SAXException;
public class XmlBeansUtilsTest extends TestCase {
public void testConvertXMLStreamValidationException() {
assertTrue("Invalid exception conversion", XmlBeansUtils.convertXmlBeansException(
new XMLStreamValidationException(XmlError.forMessage("")),
true) instanceof XmlBeansValidationFailureException);
}
public void testConvertXmlException() {
assertTrue("Invalid exception conversion", XmlBeansUtils
.convertXmlBeansException(new XmlException(""), true) instanceof XmlBeansMarshallingFailureException);
assertTrue("Invalid exception conversion", XmlBeansUtils.convertXmlBeansException(new XmlException(""),
false) instanceof XmlBeansUnmarshallingFailureException);
}
public void testConvertSAXException() {
assertTrue("Invalid exception conversion", XmlBeansUtils
.convertXmlBeansException(new SAXException(""), true) instanceof XmlBeansMarshallingFailureException);
assertTrue("Invalid exception conversion", XmlBeansUtils.convertXmlBeansException(new SAXException(""),
false) instanceof XmlBeansUnmarshallingFailureException);
}
public void testFallbackException() {
assertTrue("Invalid exception conversion",
XmlBeansUtils.convertXmlBeansException(new Exception(""), false) instanceof XmlBeansSystemException);
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,23 +18,24 @@ package org.springframework.oxm.xmlbeans;
import java.util.Collections; import java.util.Collections;
import junit.framework.TestCase;
import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlOptions;
import static org.junit.Assert.*;
import org.junit.Test;
public class XmlOptionsFactoryBeanTest extends TestCase { /**
* @author Arjen Poutsma
*/
public class XmlOptionsFactoryBeanTests {
private XmlOptionsFactoryBean factoryBean; private XmlOptionsFactoryBean factoryBean = new XmlOptionsFactoryBean();
protected void setUp() throws Exception { @Test
factoryBean = new XmlOptionsFactoryBean(); public void xmlOptionsFactoryBean() throws Exception {
}
public void testXmlOptionsFactoryBean() throws Exception {
factoryBean.setOptions(Collections.singletonMap(XmlOptions.SAVE_PRETTY_PRINT, Boolean.TRUE)); factoryBean.setOptions(Collections.singletonMap(XmlOptions.SAVE_PRETTY_PRINT, Boolean.TRUE));
factoryBean.afterPropertiesSet(); XmlOptions xmlOptions = factoryBean.getObject();
XmlOptions xmlOptions = (XmlOptions) factoryBean.getObject();
assertNotNull("No XmlOptions returned", xmlOptions); assertNotNull("No XmlOptions returned", xmlOptions);
assertTrue("Option not set", xmlOptions.hasOption(XmlOptions.SAVE_PRETTY_PRINT)); assertTrue("Option not set", xmlOptions.hasOption(XmlOptions.SAVE_PRETTY_PRINT));
assertFalse("Invalid option set", xmlOptions.hasOption(XmlOptions.LOAD_LINE_NUMBERS)); assertFalse("Invalid option set", xmlOptions.hasOption(XmlOptions.LOAD_LINE_NUMBERS));
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,8 +23,8 @@ import java.io.StringWriter;
import java.io.Writer; import java.io.Writer;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLEventWriter;
@@ -39,10 +39,11 @@ import javax.xml.transform.stream.StreamSource;
import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.custommonkey.xmlunit.XMLAssert.*;
import static org.custommonkey.xmlunit.XMLAssert.assertXpathNotExists;
import org.easymock.MockControl; import org.easymock.MockControl;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@@ -52,7 +53,10 @@ import org.xml.sax.ContentHandler;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
public class XStreamMarshallerTest { /**
* @author Arjen Poutsma
*/
public class XStreamMarshallerTests {
private static final String EXPECTED_STRING = "<flight><flightNumber>42</flightNumber></flight>"; private static final String EXPECTED_STRING = "<flight><flightNumber>42</flightNumber></flight>";
@@ -63,8 +67,8 @@ public class XStreamMarshallerTest {
@Before @Before
public void createMarshaller() throws Exception { public void createMarshaller() throws Exception {
marshaller = new XStreamMarshaller(); marshaller = new XStreamMarshaller();
Properties aliases = new Properties(); Map<String, Class> aliases = new HashMap<String, Class>();
aliases.setProperty("flight", AnnotatedFlight.class.getName()); aliases.put("flight", AnnotatedFlight.class);
marshaller.setAliases(aliases); marshaller.setAliases(aliases);
flight = new AnnotatedFlight(); flight = new AnnotatedFlight();
flight.setFlightNumber(42L); flight.setFlightNumber(42L);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2006 the original author or authors. * Copyright 2002-2009 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,7 +18,8 @@ package org.springframework.oxm.xstream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.StringReader; import java.io.StringReader;
import java.util.Properties; import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLInputFactory;
@@ -35,7 +36,10 @@ import org.xml.sax.InputSource;
import org.springframework.util.xml.StaxUtils; import org.springframework.util.xml.StaxUtils;
public class XStreamUnmarshallerTest { /**
* @author Arjen Poutsma
*/
public class XStreamUnmarshallerTests {
protected static final String INPUT_STRING = "<flight><flightNumber>42</flightNumber></flight>"; protected static final String INPUT_STRING = "<flight><flightNumber>42</flightNumber></flight>";
@@ -44,8 +48,8 @@ public class XStreamUnmarshallerTest {
@Before @Before
public void creteUnmarshaller() throws Exception { public void creteUnmarshaller() throws Exception {
unmarshaller = new XStreamMarshaller(); unmarshaller = new XStreamMarshaller();
Properties aliases = new Properties(); Map<String, Class> aliases = new HashMap<String, Class>();
aliases.setProperty("flight", AnnotatedFlight.class.getName()); aliases.put("flight", AnnotatedFlight.class);
unmarshaller.setAliases(aliases); unmarshaller.setAliases(aliases);
} }

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.xstream;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import junit.framework.TestCase;
public class XStreamUtilsTest extends TestCase {
public void testConvertStreamException() {
assertTrue("Invalid exception conversion", XStreamUtils.convertXStreamException(
new StreamException(new Exception()), true) instanceof XStreamMarshallingFailureException);
assertTrue("Invalid exception conversion", XStreamUtils.convertXStreamException(
new StreamException(new Exception()), false) instanceof XStreamUnmarshallingFailureException);
}
public void testConvertCannotResolveClassException() {
assertTrue("Invalid exception conversion", XStreamUtils.convertXStreamException(
new CannotResolveClassException(""), true) instanceof XStreamMarshallingFailureException);
assertTrue("Invalid exception conversion", XStreamUtils.convertXStreamException(
new CannotResolveClassException(""), false) instanceof XStreamUnmarshallingFailureException);
}
}