OXM is nearing completion

This commit is contained in:
Arjen Poutsma 2009-01-09 12:48:19 +00:00
parent f2329cf426
commit fc06f9ba72
99 changed files with 6343 additions and 5359 deletions

View File

@ -11,6 +11,7 @@
<include file="${spring.build.dir}/common/default-ivy-configurations.xml"/>
<conf name="commons-pool" extends="runtime" description="JARs needed to run with Commons Pool"/>
<conf name="jca" extends="runtime" description="JARs needed to develop JCA beans"/>
<conf name="oxm" extends="runtime" description="JARs needed to use the MarshallingMessageConverter"/>
</configurations>
<publications>
@ -20,18 +21,29 @@
<dependencies>
<dependency org="javax.jms" name="com.springsource.javax.jms" rev="1.1.0" conf="provided->compile"/>
<dependency org="javax.resource" name="com.springsource.javax.resource" rev="1.5.0" conf="provided, jca->compile"/>
<dependency org="javax.transaction" name="com.springsource.javax.transaction" rev="1.1.0" conf="provided->compile"/>
<dependency org="javax.resource" name="com.springsource.javax.resource" rev="1.5.0"
conf="provided, jca->compile"/>
<dependency org="javax.transaction" name="com.springsource.javax.transaction" rev="1.1.0"
conf="provided->compile"/>
<dependency org="org.aopalliance" name="com.springsource.org.aopalliance" rev="1.0.0" conf="compile->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.logging" rev="1.1.1" conf="compile->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.pool" rev="1.3.0" conf="optional, commons-pool->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.logging" rev="1.1.1"
conf="compile->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.pool" rev="1.3.0"
conf="optional, commons-pool->compile"/>
<dependency org="org.easymock" name="com.springsource.org.easymock" rev="2.3.0" conf="test->compile"/>
<dependency org="org.junit" name="com.springsource.org.junit" rev="4.5.0" conf="test->runtime"/>
<dependency org="org.springframework" name="org.springframework.aop" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.beans" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.context" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.core" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.transaction" rev="latest.integration" conf="optional, jca->compile"/>
<dependency org="org.springframework" name="org.springframework.aop" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.beans" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.context" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.core" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.oxm" rev="latest.integration"
conf="optional, oxm->compile"/>
<dependency org="org.springframework" name="org.springframework.transaction" rev="latest.integration"
conf="optional, jca->compile"/>
</dependencies>
</ivy-module>

View File

@ -5,8 +5,8 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
@ -104,10 +104,11 @@
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module" module-name="oxm" />
</component>
<component name="copyright">
<Base>
<setting name="state" value="2" />
<setting name="state" value="1" />
</Base>
</component>
</module>

View File

@ -0,0 +1,299 @@
/*
* Copyright 2007 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.jms.support.converter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.util.Assert;
/**
* Spring JMS {@link MessageConverter} that uses a {@link Marshaller} and {@link Unmarshaller}. Marshals an object to a
* {@link BytesMessage}, or to a {@link TextMessage} if the {@link #setMarshalTo marshalTo} is set to {@link
* #MARSHAL_TO_TEXT_MESSAGE}. Unmarshals from a {@link TextMessage} or {@link BytesMessage} to an object.
*
* @author Arjen Poutsma
* @see org.springframework.jms.core.JmsTemplate#convertAndSend
* @see org.springframework.jms.core.JmsTemplate#receiveAndConvert
* @since 3.0
*/
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 Unmarshaller unmarshaller;
private int marshalTo = MARSHAL_TO_BYTES_MESSAGE;
/**
* Constructs a new <code>MarshallingMessageConverter</code> with no {@link Marshaller} set. The marshaller must be set
* after construction by invoking {@link #setMarshaller(Marshaller)}.
*/
public MarshallingMessageConverter() {
}
/**
* Constructs a new <code>MarshallingMessageConverter</code> with the given {@link Marshaller} set. If the given
* {@link Marshaller} also implements the {@link Unmarshaller} interface, it is used for both marshalling and
* unmarshalling. Otherwise, an exception is thrown. <p/> Note that all {@link Marshaller} implementations in Spring-WS
* also implement the {@link Unmarshaller} interface, so that you can safely use this constructor.
*
* @param marshaller object used as marshaller and unmarshaller
* @throws IllegalArgumentException when <code>marshaller</code> does not implement the {@link Unmarshaller} interface
*/
public MarshallingMessageConverter(Marshaller marshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
if (!(marshaller instanceof Unmarshaller)) {
throw new IllegalArgumentException("Marshaller [" + marshaller + "] does not implement the Unmarshaller " +
"interface. Please set an Unmarshaller explicitely by using the " +
"AbstractMarshallingPayloadEndpoint(Marshaller, Unmarshaller) constructor.");
}
else {
this.marshaller = marshaller;
this.unmarshaller = (Unmarshaller) marshaller;
}
}
/**
* Creates a new <code>MarshallingMessageConverter</code> with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public MarshallingMessageConverter(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
this.marshaller = marshaller;
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. */
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/** Sets the {@link Unmarshaller} to be used by this message converter. */
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(marshaller, "Property 'marshaller' is required");
Assert.notNull(unmarshaller, "Property 'unmarshaller' is required");
}
/**
* Marshals the given object to a {@link TextMessage} or {@link javax.jms.BytesMessage}. The desired message type can
* be defined by setting the {@link #setMarshalTo(int) marshalTo} property.
*
* @see #marshalToTextMessage
* @see #marshalToBytesMessage
*/
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
try {
switch (marshalTo) {
case MARSHAL_TO_TEXT_MESSAGE:
return marshalToTextMessage(object, session, marshaller);
case MARSHAL_TO_BYTES_MESSAGE:
return marshalToBytesMessage(object, session, marshaller);
default:
return marshalToMessage(object, session, marshaller);
}
}
catch (MarshallingFailureException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
catch (IOException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
}
/**
* Unmarshals the given {@link Message} into an object.
*
* @see #unmarshalFromTextMessage
* @see #unmarshalFromBytesMessage
*/
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
return unmarshalFromTextMessage(textMessage, unmarshaller);
}
else if (message instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) message;
return unmarshalFromBytesMessage(bytesMessage, unmarshaller);
}
else {
return unmarshalFromMessage(message, unmarshaller);
}
}
catch (UnmarshallingFailureException ex) {
throw new MessageConversionException("Could not unmarshal message [" + message + "]", ex);
}
catch (IOException ex) {
throw new MessageConversionException("Could not unmarshal message [" + message + "]", ex);
}
}
/**
* Marshals the given object to a {@link TextMessage}.
*
* @param object the object to be marshalled
* @param session current JMS session
* @param marshaller the marshaller to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Session#createTextMessage
* @see Marshaller#marshal(Object, Result)
*/
protected TextMessage marshalToTextMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException {
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
marshaller.marshal(object, result);
return session.createTextMessage(writer.toString());
}
/**
* Marshals the given object to a {@link BytesMessage}.
*
* @param object the object to be marshalled
* @param session current JMS session
* @param marshaller the marshaller to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Session#createBytesMessage
* @see Marshaller#marshal(Object, Result)
*/
protected BytesMessage marshalToBytesMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult(bos);
marshaller.marshal(object, streamResult);
BytesMessage message = session.createBytesMessage();
message.writeBytes(bos.toByteArray());
return message;
}
/**
* Template method that allows for custom message marshalling. Invoked when {@link #setMarshalTo(int)} is not {@link
* #MARSHAL_TO_TEXT_MESSAGE} or {@link #MARSHAL_TO_BYTES_MESSAGE}. <p/> Default implemenetation throws a {@link
* MessageConversionException}.
*
* @param object the object to marshal
* @param session the JMS session
* @param marshaller the marshaller to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
*/
protected Message marshalToMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException {
throw new MessageConversionException(
"Unknown 'marshalTo' value [" + marshalTo + "]. Cannot convert object to Message");
}
/**
* Unmarshals the given {@link TextMessage} into an object.
*
* @param message the message
* @param unmarshaller the unmarshaller to use
* @return the unmarshalled object
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Unmarshaller#unmarshal(Source)
*/
protected Object unmarshalFromTextMessage(TextMessage message, Unmarshaller unmarshaller)
throws JMSException, IOException {
Source source = new StreamSource(new StringReader(message.getText()));
return unmarshaller.unmarshal(source);
}
/**
* Unmarshals the given {@link BytesMessage} into an object.
*
* @param message the message
* @param unmarshaller the unmarshaller to use
* @return the unmarshalled object
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Unmarshaller#unmarshal(Source)
*/
protected Object unmarshalFromBytesMessage(BytesMessage message, Unmarshaller unmarshaller)
throws JMSException, IOException {
byte[] bytes = new byte[(int) message.getBodyLength()];
message.readBytes(bytes);
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
StreamSource source = new StreamSource(bis);
return unmarshaller.unmarshal(source);
}
/**
* Template method that allows for custom message unmarshalling. Invoked when {@link #fromMessage(Message)} is invoked
* with a message that is not a {@link TextMessage} or {@link BytesMessage}. <p/> Default implemenetation throws a
* {@link MessageConversionException}.
*
* @param message the message
* @param unmarshaller the unmarshaller to use
* @return the unmarshalled object
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
*/
protected Object unmarshalFromMessage(Message message, Unmarshaller unmarshaller) throws JMSException, IOException {
throw new MessageConversionException(
"MarshallingMessageConverter only supports TextMessages and BytesMessages");
}
}

View File

@ -0,0 +1,117 @@
/*
* Copyright 2007 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.jms.support.converter;
import javax.jms.BytesMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
public class MarshallingMessageConverterTests {
private MarshallingMessageConverter converter;
private Marshaller marshallerMock;
private Unmarshaller unmarshallerMock;
private Session sessionMock;
@Before
public void setUp() throws Exception {
marshallerMock = createMock(Marshaller.class);
unmarshallerMock = createMock(Unmarshaller.class);
sessionMock = createMock(Session.class);
converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock);
}
@Test
public void toBytesMessage() throws Exception {
BytesMessage bytesMessageMock = createMock(BytesMessage.class);
Object toBeMarshalled = new Object();
expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock);
marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class));
bytesMessageMock.writeBytes(isA(byte[].class));
replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
converter.toMessage(toBeMarshalled, sessionMock);
verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
}
@Test
public void fromBytesMessage() throws Exception {
BytesMessage bytesMessageMock = createMock(BytesMessage.class);
Object unmarshalled = new Object();
expect(bytesMessageMock.getBodyLength()).andReturn(10L);
expect(bytesMessageMock.readBytes(isA(byte[].class))).andReturn(0);
expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled);
replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
Object result = converter.fromMessage(bytesMessageMock);
assertEquals("Invalid result", result, unmarshalled);
verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
}
@Test
public void toTextMessage() throws Exception {
converter.setMarshalTo(MarshallingMessageConverter.MARSHAL_TO_TEXT_MESSAGE);
TextMessage textMessageMock = createMock(TextMessage.class);
Object toBeMarshalled = new Object();
expect(sessionMock.createTextMessage(isA(String.class))).andReturn(textMessageMock);
marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class));
replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
converter.toMessage(toBeMarshalled, sessionMock);
verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
}
@Test
public void fromTextMessage() throws Exception {
TextMessage textMessageMock = createMock(TextMessage.class);
Object unmarshalled = new Object();
String text = "foo";
expect(textMessageMock.getText()).andReturn(text);
expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled);
replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
Object result = converter.fromMessage(textMessageMock);
assertEquals("Invalid result", result, unmarshalled);
verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
}
}

View File

@ -17,7 +17,6 @@
<conf name="jibx" extends="runtime" description="JARs needed to use JiBX"/>
<conf name="xmlbeans" extends="runtime" description="JARs needed to use XMLBeans"/>
<conf name="xstream" extends="runtime" description="JARs needed to use XStream"/>
<conf name="web" extends="runtime" description="JARs needed to use OXM in Web apps"/>
</configurations>
<publications>
@ -26,21 +25,41 @@
</publications>
<dependencies>
<dependency org="com.thoughtworks.xstream" name="com.springsource.com.thoughtworks.xstream" rev="1.3.0" conf="optional, xstream->compile"/>
<dependency org="javax.jms" name="com.springsource.javax.jms" rev="1.1.0" conf="provided, jms->compile"/>
<dependency org="javax.servlet" name="com.springsource.javax.servlet" rev="2.5.0" conf="provided, web->compile"/>
<dependency org="javax.xml.bind" name="com.springsource.javax.xml.bind" rev="2.1.7" conf="optional, jaxb->compile"/>
<dependency org="net.sourceforge.jibx" name="com.springsource.org.jibx.runtime" rev="1.1.5" conf="optional, jibx->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.logging" rev="1.1.1" conf="compile->compile"/>
<dependency org="org.apache.xmlbeans" name="com.springsource.org.apache.xmlbeans" rev="2.4.0" conf="optional, xmlbeans->compile"/>
<dependency org="org.codehaus.castor" name="com.springsource.org.castor" rev="1.2.0" conf="optional, castor->compile"/>
<dependency org="org.springframework" name="org.springframework.beans" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.core" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.jms" rev="latest.integration" conf="optional, jms->compile"/>
<dependency org="org.springframework" name="org.springframework.web.servlet" rev="latest.integration" conf="optional, web->compile"/>
<dependency org="com.thoughtworks.xstream" name="com.springsource.com.thoughtworks.xstream" rev="1.3.0"
conf="optional, xstream->compile"/>
<dependency org="javax.xml.bind" name="com.springsource.javax.xml.bind" rev="2.1.7"
conf="optional, jaxb->compile"/>
<dependency org="net.sourceforge.jibx" name="com.springsource.org.jibx.runtime" rev="1.1.5"
conf="optional, jibx->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.logging" rev="1.1.1"
conf="compile->compile"/>
<!--Xerces dependency should be removed when BRITS-259 is fixed-->
<dependency org="org.apache.xerces" name="com.springsource.org.apache.xerces" rev="2.8.1"
conf="optional, castor->compile"/>
<dependency org="org.apache.xmlbeans" name="com.springsource.org.apache.xmlbeans" rev="2.4.0"
conf="optional, xmlbeans->compile"/>
<dependency org="org.codehaus.castor" name="com.springsource.org.castor" rev="1.2.0"
conf="optional, castor->compile"/>
<dependency org="org.springframework" name="org.springframework.beans" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.context" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.core" rev="latest.integration"
conf="compile->compile"/>
<!-- test dependencies -->
<dependency org="org.junit" name="com.springsource.org.junit" rev="4.5.0" conf="test->runtime"/>
<dependency org="org.easymock" name="com.springsource.org.easymock" rev="2.3.0" conf="test->compile"/>
<dependency org="org.codehaus.jettison" name="com.springsource.org.codehaus.jettison" rev="1.0.1"
conf="test->compile"/>
<dependency org="org.custommonkey.xmlunit" name="com.springsource.org.custommonkey.xmlunit" rev="1.2.0"
conf="test->compile"/>
<!--
Set version of xml-pull to 1.1.3.4, as required by XStream. Without this explicit dependency, it will be
resolved to version 1.1.4 (due to Jibx), which is not backwards compatible, and thus causes test failures in
the XStream tests.
-->
<dependency org="org.xmlpull" name="com.springsource.org.xmlpull" rev="1.1.3.4-O" conf="test->compile"/>
</dependencies>
</ivy-module>

View File

@ -7,9 +7,19 @@
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$IVY_CACHE$/com.thoughtworks.xstream/com.springsource.com.thoughtworks.xstream/1.3.0/com.springsource.com.thoughtworks.xstream-1.3.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module" module-name="beans" />
<orderEntry type="module" module-name="core" />
<orderEntry type="module-library">
@ -83,14 +93,73 @@
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$IVY_CACHE$/com.thoughtworks.xstream/com.springsource.com.thoughtworks.xstream/1.3.0/com.springsource.com.thoughtworks.xstream-1.3.0.jar!/" />
<root url="jar://$IVY_CACHE$/org.custommonkey.xmlunit/com.springsource.org.custommonkey.xmlunit/1.2.0/com.springsource.org.custommonkey.xmlunit-1.2.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$IVY_CACHE$/com.thoughtworks.xstream/com.springsource.com.thoughtworks.xstream/1.3.0/com.springsource.com.thoughtworks.xstream-sources-1.3.0.jar!/" />
<root url="jar://$IVY_CACHE$/org.custommonkey.xmlunit/com.springsource.org.custommonkey.xmlunit/1.2.0/com.springsource.org.custommonkey.xmlunit-sources-1.2.0.jar!/" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$IVY_CACHE$/org.easymock/com.springsource.org.easymock/2.3.0/com.springsource.org.easymock-2.3.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$IVY_CACHE$/org.easymock/com.springsource.org.easymock/2.3.0/com.springsource.org.easymock-sources-2.3.0.jar!/" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.5.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module" module-name="context" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$IVY_CACHE$/org.codehaus.jettison/com.springsource.org.codehaus.jettison/1.0.1/com.springsource.org.codehaus.jettison-1.0.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$IVY_CACHE$/org.codehaus.jettison/com.springsource.org.codehaus.jettison/1.0.1/com.springsource.org.codehaus.jettison-sources-1.0.1.jar!/" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$IVY_CACHE$/org.apache.xerces/com.springsource.org.apache.xerces/2.8.1/com.springsource.org.apache.xerces-2.8.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$IVY_CACHE$/org.apache.xerces/com.springsource.org.apache.xerces/2.8.1/com.springsource.org.apache.xerces-sources-2.8.1.jar!/" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$IVY_CACHE$/org.xmlpull/com.springsource.org.xmlpull/1.1.3.4-O/com.springsource.org.xmlpull-1.1.3.4-O.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$IVY_CACHE$/org.xmlpull/com.springsource.org.xmlpull/1.1.3.4-O/com.springsource.org.xmlpull-sources-1.1.3.4-O.jar!/" />
</SOURCES>
</library>
</orderEntry>
</component>
<component name="copyright">
<Base>
<setting name="state" value="1" />
</Base>
</component>
</module>

View File

@ -49,8 +49,7 @@ import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.util.Assert;
import org.springframework.xml.transform.StaxSource;
import org.springframework.xml.transform.TraxUtils;
import org.springframework.util.xml.StaxUtils;
/**
* Abstract implementation of the <code>Marshaller</code> and <code>Unmarshaller</code> interface. This implementation
@ -58,7 +57,7 @@ import org.springframework.xml.transform.TraxUtils;
* methods.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
@ -68,17 +67,16 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
private DocumentBuilderFactory documentBuilderFactory;
/**
* Marshals the object graph with the given root into the provided <code>javax.xml.transform.Result</code>.
* <p/>
* This implementation inspects the given result, and calls <code>marshalDomResult</code>,
* <code>marshalSaxResult</code>, or <code>marshalStreamResult</code>.
* Marshals the object graph with the given root into the provided <code>javax.xml.transform.Result</code>. <p/> This
* implementation inspects the given result, and calls <code>marshalDomResult</code>, <code>marshalSaxResult</code>, or
* <code>marshalStreamResult</code>.
*
* @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
* @throws IllegalArgumentException if <code>result</code> if neither a <code>DOMResult</code>,
* <code>SAXResult</code>, <code>StreamResult</code>
* @throws IllegalArgumentException if <code>result</code> if neither a <code>DOMResult</code>, <code>SAXResult</code>,
* <code>StreamResult</code>
* @see #marshalDomResult(Object,javax.xml.transform.dom.DOMResult)
* @see #marshalSaxResult(Object,javax.xml.transform.sax.SAXResult)
* @see #marshalStreamResult(Object,javax.xml.transform.stream.StreamResult)
@ -87,7 +85,7 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
if (result instanceof DOMResult) {
marshalDomResult(graph, (DOMResult) result);
}
else if (TraxUtils.isStaxResult(result)) {
else if (StaxUtils.isStaxResult(result)) {
marshalStaxResult(graph, result);
}
else if (result instanceof SAXResult) {
@ -102,10 +100,9 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
}
/**
* Unmarshals the given provided <code>javax.xml.transform.Source</code> into an object graph.
* <p/>
* This implementation inspects the given result, and calls <code>unmarshalDomSource</code>,
* <code>unmarshalSaxSource</code>, or <code>unmarshalStreamSource</code>.
* Unmarshals the given provided <code>javax.xml.transform.Source</code> into an object graph. <p/> This implementation
* inspects the given result, and calls <code>unmarshalDomSource</code>, <code>unmarshalSaxSource</code>, or
* <code>unmarshalStreamSource</code>.
*
* @param source the source to marshal from
* @return the object graph
@ -121,7 +118,7 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
if (source instanceof DOMSource) {
return unmarshalDomSource((DOMSource) source);
}
else if (TraxUtils.isStaxSource(source)) {
else if (StaxUtils.isStaxSource(source)) {
return unmarshalStaxSource(source);
}
else if (source instanceof SAXSource) {
@ -136,8 +133,8 @@ 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 <code>DOMSource</code>. Can be overridden in subclasses, adding further initialization of the builder.
* Create a <code>DocumentBuilder</code> that this marshaller will use for creating DOM documents when passed an empty
* <code>DOMSource</code>. Can be overridden in subclasses, adding further initialization of the builder.
*
* @param factory the <code>DocumentBuilderFactory</code> that the DocumentBuilder should be created with
* @return the <code>DocumentBuilder</code>
@ -150,9 +147,9 @@ 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 <code>DOMSource</code>. The resulting <code>DocumentBuilderFactory</code> is cached, so this method will
* only be called once.
* Create a <code>DocumentBuilder</code> that this marshaller will use for creating DOM documents when passed an empty
* <code>DOMSource</code>. The resulting <code>DocumentBuilderFactory</code> is cached, so this method will only be
* called once.
*
* @return the DocumentBuilderFactory
* @throws ParserConfigurationException if thrown by JAXP methods
@ -194,22 +191,22 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
/**
* Template method for handling <code>StaxResult</code>s. This implementation defers to
* <code>marshalXMLSteamWriter</code>, or <code>marshalXMLEventConsumer</code>, depending on what is contained in
* the <code>StaxResult</code>.
* <code>marshalXMLSteamWriter</code>, or <code>marshalXMLEventConsumer</code>, depending on what is contained in the
* <code>StaxResult</code>.
*
* @param graph the root of the object graph to marshal
* @param staxResult a Spring-WS {@link 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 IllegalArgumentException if the <code>domResult</code> is empty
* @see #marshalDomNode(Object,org.w3c.dom.Node)
*/
protected void marshalStaxResult(Object graph, Result staxResult) throws XmlMappingException {
XMLStreamWriter streamWriter = TraxUtils.getXMLStreamWriter(staxResult);
XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(staxResult);
if (streamWriter != null) {
marshalXmlStreamWriter(graph, streamWriter);
}
else {
XMLEventWriter eventWriter = TraxUtils.getXMLEventWriter(staxResult);
XMLEventWriter eventWriter = StaxUtils.getXMLEventWriter(staxResult);
if (eventWriter != null) {
marshalXmlEventWriter(graph, eventWriter);
}
@ -265,9 +262,8 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
//
/**
* Template method for handling <code>DOMSource</code>s. This implementation defers to
* <code>unmarshalDomNode</code>. If the given source is empty, an empty source <code>Document</code> will be
* created as a placeholder.
* Template method for handling <code>DOMSource</code>s. This implementation defers 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>
* @return the object graph
@ -301,12 +297,12 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
* @throws XmlMappingException if the given source cannot be mapped to an object
*/
protected Object unmarshalStaxSource(Source staxSource) throws XmlMappingException {
XMLStreamReader streamReader = TraxUtils.getXMLStreamReader(staxSource);
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(staxSource);
if (streamReader != null) {
return unmarshalXmlStreamReader(streamReader);
}
else {
XMLEventReader eventReader = TraxUtils.getXMLEventReader(staxSource);
XMLEventReader eventReader = StaxUtils.getXMLEventReader(staxSource);
if (eventReader != null) {
return unmarshalXmlEventReader(eventReader);
}
@ -368,10 +364,9 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
//
/**
* Abstract template method for marshalling the given object graph to a DOM <code>Node</code>.
* <p/>
* In practice, node is be a <code>Document</code> node, a <code>DocumentFragment</code> node, or a
* <code>Element</code> node. In other words, a node that accepts children.
* Abstract template method for marshalling the given object graph to a DOM <code>Node</code>. <p/> In practice, node
* is be a <code>Document</code> node, a <code>DocumentFragment</code> node, 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 node The DOM node that will contain the result tree
@ -482,8 +477,7 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
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 inputSource the input source to parse from

View File

@ -25,7 +25,7 @@ import java.lang.reflect.Type;
* {@link Method#getGenericReturnType()}.
*
* @author Arjen Poutsma
* @since 1.0.2
* @since 3.0
*/
public interface GenericMarshaller extends Marshaller {
@ -33,8 +33,8 @@ public interface GenericMarshaller extends Marshaller {
* Indicates whether this marshaller can marshal instances of the supplied type.
*
* @param type the type that this marshaller is being asked if it can marshal
* @return <code>true</code> if this marshaller can indeed marshal instances of the supplied type;
* <code>false</code> otherwise
* @return <code>true</code> if this marshaller can indeed marshal instances of the supplied type; <code>false</code>
* otherwise
*/
boolean supports(Type type);
}

View File

@ -21,7 +21,7 @@ package org.springframework.oxm;
* @author Arjen Poutsma
* @see MarshallingFailureException
* @see UnmarshallingFailureException
* @since 1.0.0
* @since 3.0
*/
public abstract class GenericMarshallingFailureException extends XmlMappingException {

View File

@ -25,7 +25,7 @@ import java.lang.reflect.Type;
* Method#getGenericParameterTypes()} and {@link Method#getGenericReturnType()}.
*
* @author Arjen Poutsma
* @since 1.0.2
* @since 3.0
*/
public interface GenericUnmarshaller extends Unmarshaller {

View File

@ -20,14 +20,12 @@ import javax.xml.transform.Result;
/**
* Defines the contract for Object XML Mapping Marshallers. Implementations of this interface can serialize a given
* Object to an XML Stream.
* <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>java.lang.Object</code>. Instead, a object
* class must be registered with the marshaller, or have a common base class.
* Object to an XML Stream. <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>java.lang.Object</code>.
* Instead, a object class must be registered with the marshaller, or have a common base class.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public interface Marshaller {
@ -45,8 +43,8 @@ public interface Marshaller {
* 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
* @return <code>true</code> if this marshaller can indeed marshal instances of the supplied class;
* <code>false</code> otherwise
* @return <code>true</code> if this marshaller can indeed marshal instances of the supplied class; <code>false</code>
* otherwise
*/
boolean supports(Class clazz);

View File

@ -19,7 +19,7 @@ package org.springframework.oxm;
* Exception thrown on marshalling failure.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public class MarshallingFailureException extends GenericMarshallingFailureException {

View File

@ -19,7 +19,7 @@ package org.springframework.oxm;
* Superclass for exceptions that cannot be distinguished further.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public abstract class UncategorizedXmlMappingException extends XmlMappingException {

View File

@ -19,12 +19,11 @@ import java.io.IOException;
import javax.xml.transform.Source;
/**
* Defines the contract for Object XML Mapping unmarshallers.
* <p/>
* <p>Implementations of this interface can deserialize a given XML Stream to an Object graph.
* Defines the contract for Object XML Mapping unmarshallers. <p/> <p>Implementations of this interface can deserialize
* a given XML Stream to an Object graph.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public interface Unmarshaller {

View File

@ -19,7 +19,7 @@ package org.springframework.oxm;
* Exception thrown on unmarshalling failure.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public class UnmarshallingFailureException extends GenericMarshallingFailureException {

View File

@ -19,7 +19,7 @@ package org.springframework.oxm;
* Exception thrown on marshalling validation failure.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public class ValidationFailureException extends XmlMappingException {

View File

@ -50,31 +50,28 @@ import org.springframework.oxm.AbstractMarshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.xml.dom.DomContentHandler;
import org.springframework.xml.sax.SaxUtils;
import org.springframework.xml.stream.StaxEventContentHandler;
import org.springframework.xml.stream.StaxEventXmlReader;
import org.springframework.xml.stream.StaxStreamContentHandler;
import org.springframework.xml.stream.StaxStreamXmlReader;
import org.springframework.util.xml.DomUtils;
import org.springframework.util.xml.SaxUtils;
import org.springframework.util.xml.StaxUtils;
/**
* Implementation of the <code>Marshaller</code> interface for Castor. By default, Castor does not require any further
* configuration, though setting a target class or providing a mapping file can be used to have more control over the
* behavior of Castor.
* <p/>
* If a target class is specified using <code>setTargetClass</code>, the <code>CastorMarshaller</code> can only be used
* to unmarshall XML that represents that specific class. If you want to unmarshall multiple classes, you have to
*
* <p>If a target class is specified using <code>setTargetClass</code>, the <code>CastorMarshaller</code> can only be
* used to unmarshall XML that represents that specific class. If you want to unmarshall multiple classes, you have to
* provide a mapping file using <code>setMappingLocations</code>.
* <p/>
* Due to Castor's API, it is required to set the encoding used for writing to output streams. It defaults to
* <code>UTF-8</code>.
*
* <p>Due to limitations of Castor's API, it is required to set the encoding used for writing to output streams. It
* defaults to <code>UTF-8</code>.
*
* @author Arjen Poutsma
* @see #setEncoding(String)
* @see #setTargetClass(Class)
* @see #setMappingLocation(org.springframework.core.io.Resource)
* @see #setMappingLocations(org.springframework.core.io.Resource[])
* @since 1.0.0
* @see #setMappingLocation(Resource)
* @see #setMappingLocations(Resource[])
* @since 3.0
*/
public class CastorMarshaller extends AbstractMarshaller implements InitializingBean {
@ -105,8 +102,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
}
/**
* 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.
* 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)
*/
@ -120,8 +117,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
}
/**
* 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.
* 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)
*/
@ -135,8 +132,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
}
/**
* Sets whether the Castor {@link Unmarshaller} should preserve "ignorable" whitespace. Default is
* <code>false</code>.
* Sets whether the Castor {@link Unmarshaller} should preserve "ignorable" whitespace. Default is <code>false</code>.
*
* @see org.exolab.castor.xml.Unmarshaller#setWhitespacePreserve(boolean)
*/
@ -193,9 +189,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
/**
* Sets the Castor target class. If this property is set, this <code>CastorMarshaller</code> is tied to this one
* specific class. Use a mapping file for unmarshalling multiple classes.
* <p/>
* You cannot set both this property and the mapping (location).
* specific class. Use a mapping file for unmarshalling multiple classes. <p/> You cannot set both this property and
* the mapping (location).
*/
public void setTargetClass(Class targetClass) {
this.targetClass = targetClass;
@ -234,9 +229,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
}
/**
* 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.
* 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
* @throws MappingException when the mapping file cannot be loaded
@ -249,8 +243,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
XMLContext context = new XMLContext();
if (!ObjectUtils.isEmpty(mappingLocations)) {
Mapping mapping = new Mapping();
for (int i = 0; i < mappingLocations.length; i++) {
mapping.loadMapping(SaxUtils.createInputSource(mappingLocations[i]));
for (Resource mappingLocation : mappingLocations) {
mapping.loadMapping(SaxUtils.createInputSource(mappingLocation));
}
context.addMapping(mapping);
}
@ -266,7 +260,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
@Override
protected final void marshalDomNode(Object graph, Node node) throws XmlMappingException {
marshalSaxHandlers(graph, new DomContentHandler(node), null);
marshalSaxHandlers(graph, DomUtils.createContentHandler(node), null);
}
@Override
@ -292,12 +286,12 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
@Override
protected final void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter) throws XmlMappingException {
marshalSaxHandlers(graph, new StaxEventContentHandler(eventWriter), null);
marshalSaxHandlers(graph, StaxUtils.createContentHandler(eventWriter), null);
}
@Override
protected final void marshalXmlStreamWriter(Object graph, XMLStreamWriter streamWriter) throws XmlMappingException {
marshalSaxHandlers(graph, new StaxStreamContentHandler(streamWriter), null);
marshalSaxHandlers(graph, StaxUtils.createContentHandler(streamWriter), null);
}
private void marshal(Object graph, Marshaller marshaller) {
@ -311,11 +305,10 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
}
/**
* Template method that allows for customizing of the given Castor {@link Marshaller}.
* <p/>
* Default implementation invokes {@link Marshaller#setValidation(boolean)} with the property set on this
* marshaller, and calls {@link Marshaller#setNamespaceMapping(String, String)} with the {@linkplain
* #setNamespaceMappings(java.util.Properties) namespace mappings}.
* Template method that allows for customizing of the given Castor {@link Marshaller}. <p/> Default implementation
* invokes {@link Marshaller#setValidation(boolean)} with the property set on this marshaller, and calls {@link
* Marshaller#setNamespaceMapping(String, String)} with the {@linkplain #setNamespaceMappings(java.util.Properties)
* namespace mappings}.
*/
protected void customizeMarshaller(Marshaller marshaller) {
marshaller.setValidation(isValidating());
@ -365,7 +358,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
@Override
protected final Object unmarshalXmlEventReader(XMLEventReader eventReader) {
XMLReader reader = new StaxEventXmlReader(eventReader);
XMLReader reader = StaxUtils.createXMLReader(eventReader);
try {
return unmarshalSaxReader(reader, new InputSource());
}
@ -391,7 +384,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
@Override
protected final Object unmarshalXmlStreamReader(XMLStreamReader streamReader) {
XMLReader reader = new StaxStreamXmlReader(streamReader);
XMLReader reader = StaxUtils.createXMLReader(streamReader);
try {
return unmarshalSaxReader(reader, new InputSource());
}
@ -411,11 +404,10 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
}
/**
* Template method that allows for customizing of the given Castor {@link Unmarshaller}.
* <p/>
* Default implementation invokes {@link Unmarshaller#setValidation(boolean)}, {@link
* Unmarshaller#setWhitespacePreserve(boolean)}, {@link Unmarshaller#setIgnoreExtraAttributes(boolean)}, and {@link
* Unmarshaller#setIgnoreExtraElements(boolean)} with the properties set on this marshaller.
* Template method that allows for customizing of the given Castor {@link Unmarshaller}. <p/> Default implementation
* invokes {@link Unmarshaller#setValidation(boolean)}, {@link Unmarshaller#setWhitespacePreserve(boolean)}, {@link
* Unmarshaller#setIgnoreExtraAttributes(boolean)}, and {@link Unmarshaller#setIgnoreExtraElements(boolean)} with the
* properties set on this marshaller.
*/
protected void customizeUnmarshaller(Unmarshaller unmarshaller) {
unmarshaller.setValidation(isValidating());
@ -426,16 +418,14 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing
/**
* Converts the given <code>CastorException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy.
* <p/>
* The default implementation delegates to <code>CastorUtils</code>. Can be overridden in subclasses.
* <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.
* <code>org.springframework.oxm</code> hierarchy. <p/> The default implementation delegates to
* <code>CastorUtils</code>. Can be overridden in subclasses. <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>)
* @param marshalling indicates whether the exception occurs during marshalling (<code>true</code>), or unmarshalling
* (<code>false</code>)
* @return the corresponding <code>XmlMappingException</code>
* @see CastorUtils#convertXmlException
*/

View File

@ -16,6 +16,7 @@
package org.springframework.oxm.castor;
import org.exolab.castor.xml.MarshalException;
import org.springframework.oxm.MarshallingFailureException;
/**
@ -23,7 +24,7 @@ import org.springframework.oxm.MarshallingFailureException;
*
* @author Arjen Poutsma
* @see CastorUtils#convertXmlException
* @since 1.0.0
* @since 3.0
*/
public class CastorMarshallingFailureException extends MarshallingFailureException {

View File

@ -22,7 +22,7 @@ import org.springframework.oxm.UncategorizedXmlMappingException;
* distinguished further.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public class CastorSystemException extends UncategorizedXmlMappingException {

View File

@ -16,15 +16,16 @@
package org.springframework.oxm.castor;
import org.exolab.castor.xml.MarshalException;
import org.springframework.oxm.UnmarshallingFailureException;
import org.xml.sax.SAXException;
import org.springframework.oxm.UnmarshallingFailureException;
/**
* Castor-specific subclass of <code>UnmarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @see CastorUtils#convertXmlException
* @since 1.0.0
* @since 3.0
*/
public class CastorUnmarshallingFailureException extends UnmarshallingFailureException {

View File

@ -18,26 +18,26 @@ 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 1.0.0
* @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.
* <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>)
* @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) {

View File

@ -16,6 +16,7 @@
package org.springframework.oxm.castor;
import org.exolab.castor.xml.ValidationException;
import org.springframework.oxm.ValidationFailureException;
/**
@ -23,7 +24,7 @@ import org.springframework.oxm.ValidationFailureException;
*
* @author Arjen Poutsma
* @see CastorUtils#convertXmlException
* @since 1.0.0
* @since 3.0
*/
public class CastorValidationFailureException extends ValidationFailureException {

View File

@ -1,37 +0,0 @@
/*
* Copyright 2008 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.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
/**
* Parser for the <code>&lt;oxm:jaxb1-marshaller/&gt; element.
*
* @author Arjen Poutsma
* @since 1.5.0
*/
class Jaxb1MarshallerBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {
public static final String JAXB1_MARSHALLER_CLASS_NAME = "org.springframework.oxm.jaxb.Jaxb1Marshaller";
@Override
protected String getBeanClassName(Element element) {
return JAXB1_MARSHALLER_CLASS_NAME;
}
}

View File

@ -19,19 +19,20 @@ package org.springframework.oxm.config;
import java.util.Iterator;
import java.util.List;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* Parser for the <code>&lt;oxm:jaxb2-marshaller/&gt; element.
*
* @author Arjen Poutsma
* @since 1.5.0
* @since 3.0
*/
class Jaxb2MarshallerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

View File

@ -24,7 +24,7 @@ import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
* Parser for the <code>&lt;oxm:jibx-marshaller/&gt; element.
*
* @author Arjen Poutsma
* @since 1.5.0
* @since 3.0
*/
class JibxMarshallerBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {

View File

@ -23,12 +23,11 @@ import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
* {@link NamespaceHandler} for the '<code>oxm</code>' namespace.
*
* @author Arjen Poutsma
* @since 1.5.0
* @since 3.0
*/
public class OxmNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("jaxb1-marshaller", new Jaxb1MarshallerBeanDefinitionParser());
registerBeanDefinitionParser("jaxb2-marshaller", new Jaxb2MarshallerBeanDefinitionParser());
registerBeanDefinitionParser("jibx-marshaller", new JibxMarshallerBeanDefinitionParser());
registerBeanDefinitionParser("xmlbeans-marshaller", new XmlBeansMarshallerBeanDefinitionParser());

View File

@ -27,7 +27,7 @@ import org.springframework.util.StringUtils;
* Parser for the <code>&lt;oxm:xmlbeans-marshaller/&gt; element.
*
* @author Arjen Poutsma
* @since 1.5.0
* @since 3.0
*/
class XmlBeansMarshallerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

View File

@ -26,6 +26,7 @@ import javax.xml.bind.ValidationEventHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert;
@ -33,15 +34,13 @@ import org.springframework.util.StringUtils;
/**
* Abstract base class for implementations of the <code>Marshaller</code> and <code>Unmarshaller</code> interfaces that
* use JAXB. This base class is responsible for creating JAXB marshallers from a <code>JAXBContext</code>.
* <p/>
* JAXB 2.0 added breaking API changes, so specific subclasses must be used for JAXB 1.0 and 2.0
* (<code>Jaxb1Marshaller</code> and <code>Jaxb2Marshaller</code> respectivaly).
* use JAXB. This base class is responsible for creating JAXB marshallers from a <code>JAXBContext</code>. <p/> JAXB 2.0
* added breaking API changes, so specific subclasses must be used for JAXB 1.0 and 2.0 (<code>Jaxb1Marshaller</code>
* and <code>Jaxb2Marshaller</code> respectivaly).
*
* @author Arjen Poutsma
* @see Jaxb1Marshaller
* @see Jaxb2Marshaller
* @since 1.0.0
* @since 3.0
*/
public abstract class AbstractJaxbMarshaller
implements org.springframework.oxm.Marshaller, org.springframework.oxm.Unmarshaller, InitializingBean {
@ -131,9 +130,8 @@ public abstract class AbstractJaxbMarshaller
/**
* Convert the given <code>JAXBException</code> to an appropriate exception from the
* <code>org.springframework.oxm</code> hierarchy.
* <p/>
* The default implementation delegates to <code>JaxbUtils</code>. Can be overridden in subclasses.
* <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
@ -186,19 +184,17 @@ public abstract class AbstractJaxbMarshaller
}
/**
* 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 does nothing.
* 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 does nothing.
*/
protected void initJaxbMarshaller(Marshaller marshaller) throws JAXBException {
}
/**
* Template method that can overridden by concrete JAXB marshallers for custom initialization behavior. Gets called
* after creation of JAXB <code>Unmarshaller</code>, and after the respective properties have been set.
* <p/>
* Default implementation does nothing.
* after creation of JAXB <code>Unmarshaller</code>, and after the respective properties have been set. <p/> Default
* implementation does nothing.
*/
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
}

View File

@ -1,154 +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.Element;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.xml.transform.StaxResult;
import org.springframework.xml.transform.StaxSource;
import org.springframework.xml.transform.TraxUtils;
/**
* Implementation of the <code>Marshaller</code> interface for JAXB 1.0.
* <p/>
* The typical usage will be to set the <code>contextPath</code> property on this bean, possibly customize the
* marshaller and unmarshaller by setting properties, and validations, and to refer to it.
*
* @author Arjen Poutsma
* @see #setContextPath(String)
* @see #setMarshallerProperties(java.util.Map)
* @see #setUnmarshallerProperties(java.util.Map)
* @see #setValidating(boolean)
* @since 1.0.0
*/
public class Jaxb1Marshaller extends AbstractJaxbMarshaller implements BeanClassLoaderAware {
private boolean validating = false;
private ClassLoader classLoader;
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/** Set if the JAXB <code>Unmarshaller</code> should validate the incoming document. Default is <code>false</code>. */
public void setValidating(boolean validating) {
this.validating = validating;
}
public boolean supports(Class clazz) {
if (!Element.class.isAssignableFrom(clazz)) {
return false;
}
if (StringUtils.hasLength(getContextPath())) {
String className = ClassUtils.getQualifiedName(clazz);
int lastDotIndex = className.lastIndexOf('.');
if (lastDotIndex == -1) {
return false;
}
String packageName = className.substring(0, lastDotIndex);
String[] contextPaths = StringUtils.tokenizeToStringArray(getContextPath(), ":");
for (int i = 0; i < contextPaths.length; i++) {
if (contextPaths[i].equals(packageName)) {
return true;
}
}
return false;
}
return false;
}
@Override
protected final JAXBContext createJaxbContext() throws JAXBException {
if (!StringUtils.hasLength(getContextPath())) {
throw new IllegalArgumentException("contextPath is required");
}
if (logger.isInfoEnabled()) {
logger.info("Creating JAXBContext with context path [" + getContextPath() + "]");
}
return classLoader != null ? JAXBContext.newInstance(getContextPath(), classLoader) :
JAXBContext.newInstance(getContextPath());
}
@Override
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
unmarshaller.setValidating(validating);
}
public void marshal(Object graph, Result result) {
if (TraxUtils.isStaxResult(result)) {
XMLStreamWriter streamWriter = TraxUtils.getXMLStreamWriter(result);
if (streamWriter != null) {
result = new StaxResult(streamWriter);
}
else {
XMLEventWriter eventWriter = TraxUtils.getXMLEventWriter(result);
if (eventWriter != null) {
result = new StaxResult(eventWriter);
}
else {
throw new IllegalArgumentException(
"StAXResult contains neither XMLStreamWriter nor XMLEventWriter");
}
}
}
try {
createMarshaller().marshal(graph, result);
}
catch (JAXBException ex) {
throw convertJaxbException(ex);
}
}
public Object unmarshal(Source source) {
if (TraxUtils.isStaxSource(source)) {
XMLStreamReader streamReader = TraxUtils.getXMLStreamReader(source);
if (streamReader != null) {
source = new StaxSource(streamReader);
}
else {
XMLEventReader eventReader = TraxUtils.getXMLEventReader(source);
if (eventReader != null) {
source = new StaxSource(eventReader);
}
else {
throw new IllegalArgumentException(
"StAXSource contains neither XMLStreamReader nor XMLEventReader");
}
}
}
try {
return createUnmarshaller().unmarshal(source);
}
catch (JAXBException ex) {
throw convertJaxbException(ex);
}
}
}

View File

@ -58,7 +58,14 @@ import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.core.io.Resource;
@ -73,15 +80,13 @@ import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.xml.transform.TraxUtils;
import org.springframework.xml.validation.SchemaLoaderUtils;
import org.springframework.util.xml.SaxUtils;
import org.springframework.util.xml.StaxUtils;
/**
* Implementation of the <code>Marshaller</code> interface for JAXB 2.0.
* <p/>
* The typical usage will be to set either the <code>contextPath</code> or the <code>classesToBeBound</code> property on
* this bean, possibly customize the marshaller and unmarshaller by setting properties, schemas, adapters, and
* listeners, and to refer to it.
* Implementation of the <code>Marshaller</code> interface for JAXB 2.0. <p/> The typical usage will be to set either
* the <code>contextPath</code> or the <code>classesToBeBound</code> property on this bean, possibly customize the
* marshaller and unmarshaller by setting properties, schemas, adapters, and listeners, and to refer to it.
*
* @author Arjen Poutsma
* @see #setContextPath(String)
@ -94,7 +99,7 @@ import org.springframework.xml.validation.SchemaLoaderUtils;
* @see #setMarshallerListener(javax.xml.bind.Marshaller.Listener)
* @see #setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener)
* @see #setAdapters(javax.xml.bind.annotation.adapters.XmlAdapter[])
* @since 1.0.0
* @since 3.0
*/
public class Jaxb2Marshaller extends AbstractJaxbMarshaller
implements MimeMarshaller, MimeUnmarshaller, GenericMarshaller, GenericUnmarshaller, BeanClassLoaderAware {
@ -155,8 +160,8 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
}
/**
* Indicates whether MTOM support should be enabled or not. Default is <code>false</code>, marshalling using
* XOP/MTOM is not enabled.
* 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;
@ -250,8 +255,8 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
}
String packageName = className.substring(0, lastDotIndex);
String[] contextPaths = StringUtils.tokenizeToStringArray(getContextPath(), ":");
for (int i = 0; i < contextPaths.length; i++) {
if (contextPaths[i].equals(packageName)) {
for (String contextPath : contextPaths) {
if (contextPath.equals(packageName)) {
return true;
}
}
@ -281,7 +286,7 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
logger.debug(
"Setting validation schema to " + StringUtils.arrayToCommaDelimitedString(schemaResources));
}
schema = SchemaLoaderUtils.loadSchema(schemaResources, schemaLanguage);
schema = loadSchema(schemaResources, schemaLanguage);
}
if (StringUtils.hasLength(getContextPath())) {
return createJaxbContextFromContextPath();
@ -294,14 +299,29 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
}
}
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
Assert.notEmpty(resources, "No resources given");
Assert.hasLength(schemaLanguage, "No schema language provided");
Source[] schemaSources = new Source[resources.length];
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
for (int i = 0; i < resources.length; i++) {
Assert.notNull(resources[i], "Resource is null");
Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
InputSource inputSource = SaxUtils.createInputSource(resources[i]);
schemaSources[i] = new SAXSource(xmlReader, inputSource);
}
SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
return schemaFactory.newSchema(schemaSources);
}
private JAXBContext createJaxbContextFromContextPath() throws JAXBException {
if (logger.isInfoEnabled()) {
logger.info("Creating JAXBContext with context path [" + getContextPath() + "]");
}
if (jaxbContextProperties != null) {
if (classLoader != null) {
return JAXBContext
.newInstance(getContextPath(), classLoader, jaxbContextProperties);
return JAXBContext.newInstance(getContextPath(), classLoader, jaxbContextProperties);
}
else {
return JAXBContext
@ -340,8 +360,8 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
marshaller.setListener(marshallerListener);
}
if (adapters != null) {
for (int i = 0; i < adapters.length; i++) {
marshaller.setAdapter(adapters[i]);
for (XmlAdapter adapter : adapters) {
marshaller.setAdapter(adapter);
}
}
}
@ -355,8 +375,8 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
unmarshaller.setListener(unmarshallerListener);
}
if (adapters != null) {
for (int i = 0; i < adapters.length; i++) {
unmarshaller.setAdapter(adapters[i]);
for (XmlAdapter adapter : adapters) {
unmarshaller.setAdapter(adapter);
}
}
}
@ -375,7 +395,7 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
if (mtomEnabled && mimeContainer != null) {
marshaller.setAttachmentMarshaller(new Jaxb2AttachmentMarshaller(mimeContainer));
}
if (TraxUtils.isStaxResult(result)) {
if (StaxUtils.isStaxResult(result)) {
marshalStaxResult(marshaller, graph, result);
}
else {
@ -388,12 +408,12 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
}
private void marshalStaxResult(Marshaller jaxbMarshaller, Object graph, Result staxResult) throws JAXBException {
XMLStreamWriter streamWriter = TraxUtils.getXMLStreamWriter(staxResult);
XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(staxResult);
if (streamWriter != null) {
jaxbMarshaller.marshal(graph, streamWriter);
}
else {
XMLEventWriter eventWriter = TraxUtils.getXMLEventWriter(staxResult);
XMLEventWriter eventWriter = StaxUtils.getXMLEventWriter(staxResult);
if (eventWriter != null) {
jaxbMarshaller.marshal(graph, eventWriter);
}
@ -417,7 +437,7 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
if (mtomEnabled && mimeContainer != null) {
unmarshaller.setAttachmentUnmarshaller(new Jaxb2AttachmentUnmarshaller(mimeContainer));
}
if (TraxUtils.isStaxSource(source)) {
if (StaxUtils.isStaxSource(source)) {
return unmarshalStaxSource(unmarshaller, source);
}
else {
@ -430,12 +450,12 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
}
private Object unmarshalStaxSource(Unmarshaller jaxbUnmarshaller, Source staxSource) throws JAXBException {
XMLStreamReader streamReader = TraxUtils.getXMLStreamReader(staxSource);
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(staxSource);
if (streamReader != null) {
return jaxbUnmarshaller.unmarshal(streamReader);
}
else {
XMLEventReader eventReader = TraxUtils.getXMLEventReader(staxSource);
XMLEventReader eventReader = StaxUtils.getXMLEventReader(staxSource);
if (eventReader != null) {
return jaxbUnmarshaller.unmarshal(eventReader);
}
@ -453,7 +473,7 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
private final MimeContainer mimeContainer;
public Jaxb2AttachmentMarshaller(MimeContainer mimeContainer) {
private Jaxb2AttachmentMarshaller(MimeContainer mimeContainer) {
this.mimeContainer = mimeContainer;
}
@ -510,7 +530,7 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
private final MimeContainer mimeContainer;
public Jaxb2AttachmentUnmarshaller(MimeContainer mimeContainer) {
private Jaxb2AttachmentUnmarshaller(MimeContainer mimeContainer) {
this.mimeContainer = mimeContainer;
}
@ -559,7 +579,7 @@ public class Jaxb2Marshaller extends AbstractJaxbMarshaller
private int length;
public ByteArrayDataSource(String contentType, byte[] data, int offset, int length) {
private ByteArrayDataSource(String contentType, byte[] data, int offset, int length) {
this.contentType = contentType;
this.data = data;
this.offset = offset;

View File

@ -24,7 +24,7 @@ import org.springframework.oxm.MarshallingFailureException;
*
* @author Arjen Poutsma
* @see JaxbUtils#convertJaxbException
* @since 1.0.0
* @since 3.0
*/
public class JaxbMarshallingFailureException extends MarshallingFailureException {

View File

@ -25,7 +25,7 @@ import org.springframework.oxm.UncategorizedXmlMappingException;
*
* @author Arjen Poutsma
* @see JaxbUtils#convertJaxbException(javax.xml.bind.JAXBException)
* @since 1.0.0
* @since 3.0
*/
public class JaxbSystemException extends UncategorizedXmlMappingException {

View File

@ -24,7 +24,7 @@ import org.springframework.oxm.UnmarshallingFailureException;
* JAXB-specific subclass of <code>UnmarshallingFailureException</code>.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public class JaxbUnmarshallingFailureException extends UnmarshallingFailureException {

View File

@ -27,7 +27,7 @@ import org.springframework.util.ClassUtils;
* Generic utility methods for working with JAXB. Mainly for internal use within the framework.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public abstract class JaxbUtils {

View File

@ -24,7 +24,7 @@ import org.springframework.oxm.ValidationFailureException;
*
* @author Arjen Poutsma
* @see JaxbUtils#convertJaxbException
* @since 1.0.0
* @since 3.0
*/
public class JaxbValidationFailureException extends ValidationFailureException {

View File

@ -60,19 +60,17 @@ import org.springframework.oxm.AbstractMarshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.xml.stream.StaxEventContentHandler;
import org.springframework.xml.stream.XmlEventStreamReader;
import org.springframework.util.xml.StaxUtils;
/**
* Implementation of the <code>Marshaller</code> and <code>Unmarshaller</code> interfaces for JiBX.
* <p/>
* The typical usage will be to set the <code>targetClass</code> and optionally the <code>bindingName</code> property on
* this bean, and to refer to it.
* Implementation of the <code>Marshaller</code> and <code>Unmarshaller</code> interfaces for JiBX. <p/> The typical
* usage will be to set the <code>targetClass</code> and optionally the <code>bindingName</code> property on this bean,
* and to refer to it.
*
* @author Arjen Poutsma
* @see org.jibx.runtime.IMarshallingContext
* @see org.jibx.runtime.IUnmarshallingContext
* @since 1.0.0
* @since 3.0
*/
public class JibxMarshaller extends AbstractMarshaller implements InitializingBean {
@ -142,8 +140,8 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
Assert.notNull(clazz, "'clazz' must not be null");
String[] mappedClasses = bindingFactory.getMappedClasses();
String className = clazz.getName();
for (int i = 0; i < mappedClasses.length; i++) {
if (className.equals(mappedClasses[i])) {
for (String mappedClass : mappedClasses) {
if (className.equals(mappedClass)) {
return true;
}
}
@ -152,16 +150,13 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
/**
* 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.
* <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>)
* @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)
*/
@ -254,7 +249,7 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
@Override
protected void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter) {
ContentHandler contentHandler = new StaxEventContentHandler(eventWriter);
ContentHandler contentHandler = StaxUtils.createContentHandler(eventWriter);
marshalSaxHandlers(graph, contentHandler, null);
}
@ -300,7 +295,7 @@ public class JibxMarshaller extends AbstractMarshaller implements InitializingBe
@Override
protected Object unmarshalXmlEventReader(XMLEventReader eventReader) {
try {
XMLStreamReader streamReader = new XmlEventStreamReader(eventReader);
XMLStreamReader streamReader = StaxUtils.createEventStreamReader(eventReader);
return unmarshalXmlStreamReader(streamReader);
}
catch (XMLStreamException ex) {

View File

@ -17,6 +17,7 @@
package org.springframework.oxm.jibx;
import org.jibx.runtime.JiBXException;
import org.springframework.oxm.MarshallingFailureException;
/**
@ -24,7 +25,7 @@ import org.springframework.oxm.MarshallingFailureException;
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 1.0.0
* @since 3.0
*/
public class JibxMarshallingFailureException extends MarshallingFailureException {

View File

@ -24,7 +24,7 @@ import org.springframework.oxm.UncategorizedXmlMappingException;
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 1.0.0
* @since 3.0
*/
public class JibxSystemException extends UncategorizedXmlMappingException {

View File

@ -17,6 +17,7 @@
package org.springframework.oxm.jibx;
import org.jibx.runtime.JiBXException;
import org.springframework.oxm.UnmarshallingFailureException;
/**
@ -24,7 +25,7 @@ import org.springframework.oxm.UnmarshallingFailureException;
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 1.0.0
* @since 3.0
*/
public class JibxUnmarshallingFailureException extends UnmarshallingFailureException {

View File

@ -18,26 +18,26 @@ 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 1.0.0
* @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.
* <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>)
* @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) {

View File

@ -17,6 +17,7 @@
package org.springframework.oxm.jibx;
import org.jibx.runtime.ValidationException;
import org.springframework.oxm.ValidationFailureException;
/**
@ -24,7 +25,7 @@ import org.springframework.oxm.ValidationFailureException;
*
* @author Arjen Poutsma
* @see JibxUtils#convertJibxException(org.jibx.runtime.JiBXException,boolean)
* @since 1.0.0
* @since 3.0
*/
public class JibxValidationFailureException extends ValidationFailureException {

View File

@ -23,7 +23,7 @@ import javax.activation.DataHandler;
*
* @author Arjen Poutsma
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
* @since 1.0.0
* @since 3.0
*/
public interface MimeContainer {

View File

@ -30,7 +30,7 @@ import org.springframework.oxm.XmlMappingException;
* @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 1.0.0
* @since 3.0
*/
public interface MimeMarshaller extends Marshaller {

View File

@ -30,7 +30,7 @@ import org.springframework.oxm.XmlMappingException;
* @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 1.0.0
* @since 3.0
*/
public interface MimeUnmarshaller extends Unmarshaller {

View File

@ -1,306 +0,0 @@
/*
* Copyright 2007 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.support;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.util.Assert;
/**
* Spring JMS {@link MessageConverter} that uses a {@link Marshaller} and {@link Unmarshaller}. Marshals an object to a
* {@link BytesMessage}, or to a {@link TextMessage} if the {@link #setMarshalTo marshalTo} is set to {@link
* #MARSHAL_TO_TEXT_MESSAGE}. Unmarshals from a {@link TextMessage} or {@link BytesMessage} to an object.
*
* @author Arjen Poutsma
* @see org.springframework.jms.core.JmsTemplate#convertAndSend
* @see org.springframework.jms.core.JmsTemplate#receiveAndConvert
* @since 1.5.1
*/
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 Unmarshaller unmarshaller;
private int marshalTo = MARSHAL_TO_BYTES_MESSAGE;
/**
* Constructs a new <code>MarshallingMessageConverter</code> with no {@link Marshaller} set. The marshaller must be
* set after construction by invoking {@link #setMarshaller(Marshaller)}.
*/
public MarshallingMessageConverter() {
}
/**
* Constructs a new <code>MarshallingMessageConverter</code> with the given {@link Marshaller} set. If the given
* {@link Marshaller} also implements the {@link Unmarshaller} interface, it is used for both marshalling and
* unmarshalling. Otherwise, an exception is thrown.
* <p/>
* Note that all {@link Marshaller} implementations in Spring-WS also implement the {@link Unmarshaller} interface,
* so that you can safely use this constructor.
*
* @param marshaller object used as marshaller and unmarshaller
* @throws IllegalArgumentException when <code>marshaller</code> does not implement the {@link Unmarshaller}
* interface
*/
public MarshallingMessageConverter(Marshaller marshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
if (!(marshaller instanceof Unmarshaller)) {
throw new IllegalArgumentException("Marshaller [" + marshaller + "] does not implement the Unmarshaller " +
"interface. Please set an Unmarshaller explicitely by using the " +
"AbstractMarshallingPayloadEndpoint(Marshaller, Unmarshaller) constructor.");
}
else {
this.marshaller = marshaller;
this.unmarshaller = (Unmarshaller) marshaller;
}
}
/**
* Creates a new <code>MarshallingMessageConverter</code> with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public MarshallingMessageConverter(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
this.marshaller = marshaller;
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. */
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/** Sets the {@link Unmarshaller} to be used by this message converter. */
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(marshaller, "Property 'marshaller' is required");
Assert.notNull(unmarshaller, "Property 'unmarshaller' is required");
}
/**
* Marshals the given object to a {@link TextMessage} or {@link javax.jms.BytesMessage}. The desired message type
* can be defined by setting the {@link #setMarshalTo(int) marshalTo} property.
*
* @see #marshalToTextMessage
* @see #marshalToBytesMessage
*/
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
try {
switch (marshalTo) {
case MARSHAL_TO_TEXT_MESSAGE:
return marshalToTextMessage(object, session, marshaller);
case MARSHAL_TO_BYTES_MESSAGE:
return marshalToBytesMessage(object, session, marshaller);
default:
return marshalToMessage(object, session, marshaller);
}
}
catch (MarshallingFailureException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
catch (IOException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
}
/**
* Unmarshals the given {@link Message} into an object.
*
* @see #unmarshalFromTextMessage
* @see #unmarshalFromBytesMessage
*/
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
return unmarshalFromTextMessage(textMessage, unmarshaller);
}
else if (message instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) message;
return unmarshalFromBytesMessage(bytesMessage, unmarshaller);
}
else {
return unmarshalFromMessage(message, unmarshaller);
}
}
catch (UnmarshallingFailureException ex) {
throw new MessageConversionException("Could not unmarshal message [" + message + "]", ex);
}
catch (IOException ex) {
throw new MessageConversionException("Could not unmarshal message [" + message + "]", ex);
}
}
/**
* Marshals the given object to a {@link TextMessage}.
*
* @param object the object to be marshalled
* @param session current JMS session
* @param marshaller the marshaller to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Session#createTextMessage
* @see Marshaller#marshal(Object, Result)
*/
protected TextMessage marshalToTextMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException {
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
marshaller.marshal(object, result);
return session.createTextMessage(writer.toString());
}
/**
* Marshals the given object to a {@link BytesMessage}.
*
* @param object the object to be marshalled
* @param session current JMS session
* @param marshaller the marshaller to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Session#createBytesMessage
* @see Marshaller#marshal(Object, Result)
*/
protected BytesMessage marshalToBytesMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult(bos);
marshaller.marshal(object, streamResult);
BytesMessage message = session.createBytesMessage();
message.writeBytes(bos.toByteArray());
return message;
}
/**
* Template method that allows for custom message marshalling. Invoked when {@link #setMarshalTo(int)} is not {@link
* #MARSHAL_TO_TEXT_MESSAGE} or {@link #MARSHAL_TO_BYTES_MESSAGE}.
* <p/>
* Default implemenetation throws a {@link MessageConversionException}.
*
* @param object the object to marshal
* @param session the JMS session
* @param marshaller the marshaller to use
* @return the resulting message
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
*/
protected Message marshalToMessage(Object object, Session session, Marshaller marshaller)
throws JMSException, IOException {
throw new MessageConversionException(
"Unknown 'marshalTo' value [" + marshalTo + "]. Cannot convert object to Message");
}
/**
* Unmarshals the given {@link TextMessage} into an object.
*
* @param message the message
* @param unmarshaller the unmarshaller to use
* @return the unmarshalled object
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Unmarshaller#unmarshal(Source)
*/
protected Object unmarshalFromTextMessage(TextMessage message, Unmarshaller unmarshaller)
throws JMSException, IOException {
Source source = new StreamSource(new StringReader(message.getText()));
return unmarshaller.unmarshal(source);
}
/**
* Unmarshals the given {@link BytesMessage} into an object.
*
* @param message the message
* @param unmarshaller the unmarshaller to use
* @return the unmarshalled object
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
* @see Unmarshaller#unmarshal(Source)
*/
protected Object unmarshalFromBytesMessage(BytesMessage message, Unmarshaller unmarshaller)
throws JMSException, IOException {
byte[] bytes = new byte[(int) message.getBodyLength()];
message.readBytes(bytes);
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
StreamSource source = new StreamSource(bis);
return unmarshaller.unmarshal(source);
}
/**
* Template method that allows for custom message unmarshalling. Invoked when {@link #fromMessage(Message)} is
* invoked with a message that is not a {@link TextMessage} or {@link BytesMessage}.
* <p/>
* Default implemenetation throws a {@link MessageConversionException}.
*
* @param message the message
* @param unmarshaller the unmarshaller to use
* @return the unmarshalled object
* @throws JMSException if thrown by JMS methods
* @throws IOException in case of I/O errors
*/
protected Object unmarshalFromMessage(Message message, Unmarshaller unmarshaller) throws JMSException, IOException {
throw new MessageConversionException(
"MarshallingMessageConverter only supports TextMessages and BytesMessages");
}
}

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");
* you may not use this file except in compliance with the License.
@ -21,26 +21,34 @@ import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert;
import org.springframework.xml.sax.AbstractXmlReader;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert;
/**
* {@link Source} implementation that uses a {@link Marshaller}.Can be constructed with a <code>Marshaller</code> and an
* object to be marshalled.
* <p/>
* Even though <code>StaxSource</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
* to use the <code>XMLReader</code> obtained via {@link #getXMLReader()} to parse the input source obtained via {@link
* #getInputSource()}. Calling {@link #setXMLReader(org.xml.sax.XMLReader)} or {@link
* #setInputSource(org.xml.sax.InputSource)} will result in <code>UnsupportedOperationException</code>s.
* #getInputSource()}. Calling {@link #setXMLReader(XMLReader)} or {@link #setInputSource(InputSource)} will result in
* <code>UnsupportedOperationException</code>s.
*
* @author Arjen Poutsma
* @see javax.xml.transform.Transformer
* @since 1.0.0
* @since 3.0
*/
public class MarshallingSource extends SAXSource {
@ -55,12 +63,11 @@ public class MarshallingSource extends SAXSource {
* @param content the object to be marshalled
*/
public MarshallingSource(Marshaller marshaller, Object content) {
super(new MarshallingXMLReader(marshaller, content), new InputSource());
Assert.notNull(marshaller, "'marshaller' must not be null");
Assert.notNull(content, "'content' must not be null");
this.marshaller = marshaller;
this.content = content;
setXMLReader(new MarshallingXmlReader());
setInputSource(new InputSource());
}
/** Returns the <code>Marshaller</code> used by this <code>MarshallingSource</code>. */
@ -73,7 +80,110 @@ public class MarshallingSource extends SAXSource {
return content;
}
private class MarshallingXmlReader extends AbstractXmlReader {
/**
* Throws a <code>UnsupportedOperationException</code>.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setInputSource(InputSource inputSource) {
throw new UnsupportedOperationException("setInputSource is not supported");
}
/**
* Throws a <code>UnsupportedOperationException</code>.
*
* @throws UnsupportedOperationException always
*/
@Override
public void setXMLReader(XMLReader reader) {
throw new UnsupportedOperationException("setXMLReader is not supported");
}
private static class MarshallingXMLReader implements XMLReader {
private final Marshaller marshaller;
private final Object content;
private DTDHandler dtdHandler;
private ContentHandler contentHandler;
private EntityResolver entityResolver;
private ErrorHandler errorHandler;
private LexicalHandler lexicalHandler;
private MarshallingXMLReader(Marshaller marshaller, Object content) {
Assert.notNull(marshaller, "'marshaller' must not be null");
Assert.notNull(content, "'content' must not be null");
this.marshaller = marshaller;
this.content = content;
}
public ContentHandler getContentHandler() {
return contentHandler;
}
public void setContentHandler(ContentHandler contentHandler) {
this.contentHandler = contentHandler;
}
public void setDTDHandler(DTDHandler dtdHandler) {
this.dtdHandler = dtdHandler;
}
public DTDHandler getDTDHandler() {
return dtdHandler;
}
public EntityResolver getEntityResolver() {
return entityResolver;
}
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
public ErrorHandler getErrorHandler() {
return errorHandler;
}
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
protected LexicalHandler getLexicalHandler() {
return lexicalHandler;
}
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
throw new SAXNotRecognizedException(name);
}
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
throw new SAXNotRecognizedException(name);
}
public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
return lexicalHandler;
}
else {
throw new SAXNotRecognizedException(name);
}
}
public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
lexicalHandler = (LexicalHandler) value;
}
else {
throw new SAXNotRecognizedException(name);
}
}
public void parse(InputSource input) throws IOException, SAXException {
parse();

View File

@ -1,134 +0,0 @@
/*
* Copyright 2007 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.support;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamResult;
import org.springframework.beans.BeansException;
import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
/**
* Spring-MVC {@link View} that allows for response context to be rendered as the result of marshalling by a {@link
* Marshaller}.
* <p/>
* The Object to be marshalled is supplied as a parameter in the model and then {@linkplain #locateToBeMarshalled(Map)
* detected} during response rendering. Users can either specify a specific entry in the model via the {@link
* #setModelKey(String) sourceKey} property or have Spring locate the Source object.
*
* @author Arjen Poutsma
* @since 1.5.1
*/
public class MarshallingView extends AbstractUrlBasedView {
/** Default content type. Overridable as bean property. */
public static final String DEFAULT_CONTENT_TYPE = "application/xml";
private Marshaller marshaller;
private String modelKey;
/**
* Constructs a new <code>MarshallingView</code> with no {@link Marshaller} set. The marshaller must be set after
* construction by invoking {@link #setMarshaller(Marshaller)}.
*/
public MarshallingView() {
setContentType(DEFAULT_CONTENT_TYPE);
}
/** Constructs a new <code>MarshallingView</code> with the given {@link Marshaller} set. */
public MarshallingView(Marshaller marshaller) {
Assert.notNull(marshaller, "'marshaller' must not be null");
setContentType(DEFAULT_CONTENT_TYPE);
this.marshaller = marshaller;
}
/** Sets the {@link Marshaller} to be used by this view. */
public void setMarshaller(Marshaller marshaller) {
Assert.notNull(marshaller, "'marshaller' must not be null");
this.marshaller = marshaller;
}
/**
* Set the name of the model key that represents the object to be marshalled. If not specified, the model map will
* be searched for a supported value type.
*
* @see Marshaller#supports(Class)
*/
public void setModelKey(String modelKey) {
this.modelKey = modelKey;
}
@Override
protected void initApplicationContext() throws BeansException {
Assert.notNull(marshaller, "Property 'marshaller' is required");
}
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Object toBeMarshalled = locateToBeMarshalled(model);
if (toBeMarshalled == null) {
throw new ServletException("Unable to locate object to be marshalled in model: " + model);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
marshaller.marshal(toBeMarshalled, new StreamResult(bos));
response.setContentType(getContentType());
response.setContentLength(bos.size());
ServletOutputStream out = response.getOutputStream();
bos.writeTo(out);
out.flush();
}
/**
* Locates the object to be marshalled. The default implementation first attempts to look under the configured
* {@linkplain #setModelKey(String) model key}, if any, before attempting to locate an object of {@linkplain
* Marshaller#supports(Class) supported type}.
*
* @param model the model Map
* @return the Object to be marshalled (or <code>null</code> if none found)
* @throws ServletException if the model object specified by the {@linkplain #setModelKey(String) model key} is not
* supported by the marshaller
* @see #setModelKey(String)
*/
protected Object locateToBeMarshalled(Map model) throws ServletException {
if (this.modelKey != null) {
Object o = model.get(this.modelKey);
if (!this.marshaller.supports(o.getClass())) {
throw new ServletException("Model object [" + o + "] retrieved via key [" + modelKey +
"] is not supported by the Marshaller");
}
return o;
}
for (Object o : model.values()) {
if (this.marshaller.supports(o.getClass())) {
return o;
}
}
return null;
}
}

View File

@ -19,12 +19,6 @@ import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlSaxHandler;
import org.apache.xmlbeans.XmlValidationError;
import org.springframework.oxm.AbstractMarshaller;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.xml.stream.StaxEventContentHandler;
import org.springframework.xml.stream.StaxEventXmlReader;
import org.springframework.xml.stream.StaxStreamContentHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@ -36,22 +30,24 @@ import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.springframework.oxm.AbstractMarshaller;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.xml.StaxUtils;
/**
* Implementation of the {@link Marshaller} interface for XMLBeans. Further options can be set by setting the
* <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 the {@link
* #validate(XmlObject)} method directly. Invalid objects will result in an {@link XmlBeansValidationFailureException}.
* <p/>
* <strong>Note</strong> that due to the nature of XMLBeans, this marshaller requires all passed objects to be of type
* {@link XmlObject}.
* instances. <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/> <strong>Note</strong> that due to the nature of XMLBeans, this marshaller
* requires all passed objects to be of type {@link XmlObject}.
*
* @author Arjen Poutsma
* @see #setXmlOptions(org.apache.xmlbeans.XmlOptions)
* @see XmlOptionsFactoryBean
* @see #setValidating(boolean)
* @since 1.0.0
* @since 3.0
*/
public class XmlBeansMarshaller extends AbstractMarshaller {
@ -124,13 +120,13 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
@Override
protected final void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter) {
ContentHandler contentHandler = new StaxEventContentHandler(eventWriter);
ContentHandler contentHandler = StaxUtils.createContentHandler(eventWriter);
marshalSaxHandlers(graph, contentHandler, null);
}
@Override
protected final void marshalXmlStreamWriter(Object graph, XMLStreamWriter streamWriter) throws XmlMappingException {
ContentHandler contentHandler = new StaxStreamContentHandler(streamWriter);
ContentHandler contentHandler = StaxUtils.createContentHandler(streamWriter);
marshalSaxHandlers(graph, contentHandler, null);
}
@ -200,7 +196,7 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
@Override
protected final Object unmarshalXmlEventReader(XMLEventReader eventReader) throws XmlMappingException {
XMLReader reader = new StaxEventXmlReader(eventReader);
XMLReader reader = StaxUtils.createXMLReader(eventReader);
try {
return unmarshalSaxReader(reader, new InputSource());
}
@ -223,16 +219,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
* 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>)
* @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)
*/
@ -254,14 +247,14 @@ public class XmlBeansMarshaller extends AbstractMarshaller {
List errorsList = new ArrayList();
validateOptions.setErrorListener(errorsList);
if (!object.validate(validateOptions)) {
StringBuffer buffer = new StringBuffer("Could not validate XmlObject :");
StringBuilder builder = new StringBuilder("Could not validate XmlObject :");
for (Iterator iterator = errorsList.iterator(); iterator.hasNext();) {
XmlError xmlError = (XmlError) iterator.next();
if (xmlError instanceof XmlValidationError) {
buffer.append(xmlError.toString());
builder.append(xmlError.toString());
}
}
XmlException ex = new XmlException(buffer.toString(), null, errorsList);
XmlException ex = new XmlException(builder.toString(), null, errorsList);
throw new XmlBeansValidationFailureException(ex);
}
}

View File

@ -16,15 +16,16 @@
package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XmlException;
import org.springframework.oxm.MarshallingFailureException;
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 1.0.0
* @since 3.0
*/
public class XmlBeansMarshallingFailureException extends MarshallingFailureException {

View File

@ -22,7 +22,7 @@ import org.springframework.oxm.UncategorizedXmlMappingException;
* distinguished further.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public class XmlBeansSystemException extends UncategorizedXmlMappingException {

View File

@ -16,15 +16,16 @@
package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XmlException;
import org.springframework.oxm.UnmarshallingFailureException;
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 1.0.0
* @since 3.0
*/
public class XmlBeansUnmarshallingFailureException extends UnmarshallingFailureException {

View File

@ -17,27 +17,26 @@ package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XMLStreamValidationException;
import org.apache.xmlbeans.XmlException;
import org.springframework.oxm.XmlMappingException;
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 1.0.0
* @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.
* 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>)
* @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) {

View File

@ -17,6 +17,7 @@ package org.springframework.oxm.xmlbeans;
import org.apache.xmlbeans.XMLStreamValidationException;
import org.apache.xmlbeans.XmlException;
import org.springframework.oxm.ValidationFailureException;
/**
@ -24,7 +25,7 @@ import org.springframework.oxm.ValidationFailureException;
*
* @author Arjen Poutsma
* @see org.springframework.oxm.xmlbeans.XmlBeansUtils#convertXmlBeansException
* @since 1.0.0
* @since 3.0
*/
public class XmlBeansValidationFailureException extends ValidationFailureException {

View File

@ -20,19 +20,19 @@ import java.util.Iterator;
import java.util.Map;
import org.apache.xmlbeans.XmlOptions;
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/>
* Factory bean that configures an XMLBeans <code>XmlOptions</code> object 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 <code>XmlBeansMarshaller</code>.
*
* @author Arjen Poutsma
* @see XmlOptions
* @see #setOptions(java.util.Map)
* @see XmlBeansMarshaller#setXmlOptions(org.apache.xmlbeans.XmlOptions)
* @since 1.0.0
* @since 3.0
*/
public class XmlOptionsFactoryBean implements FactoryBean, InitializingBean {

View File

@ -1,53 +0,0 @@
/*
* Copyright 2007 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.XStream;
import com.thoughtworks.xstream.annotations.Annotations;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.springframework.util.Assert;
/**
* Subclass of the {@link XStreamMarshaller} that supports JDK 1.5+ annotation metadata for aliases.
*
* @author Arjen Poutsma
* @see XStreamAlias
* @since 1.0.2
*/
public class AnnotationXStreamMarshaller extends XStreamMarshaller {
/**
* Sets the classes, for which mappings will be read from class-level JDK 1.5+ annotation metadata.
*
* @see Annotations#configureAliases(XStream, Class[])
*/
public void setAnnotatedClass(Class<?> annotatedClass) {
Assert.notNull(annotatedClass, "'annotatedClass' must not be null");
Annotations.configureAliases(getXStream(), annotatedClass);
}
/**
* Sets annotated classes, for which aliases will be read from class-level JDK 1.5+ annotation metadata.
*
* @see Annotations#configureAliases(XStream, Class[])
*/
public void setAnnotatedClasses(Class<?>[] annotatedClasses) {
Assert.notEmpty(annotatedClasses, "'annotatedClasses' must not be empty");
Annotations.configureAliases(getXStream(), annotatedClasses);
}
}

View File

@ -58,20 +58,17 @@ import org.xml.sax.ext.LexicalHandler;
import org.springframework.beans.propertyeditors.ClassEditor;
import org.springframework.oxm.AbstractMarshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.xml.stream.StaxEventContentHandler;
import org.springframework.xml.stream.XmlEventStreamReader;
import org.springframework.util.xml.StaxUtils;
/**
* Implementation of the <code>Marshaller</code> interface for XStream. By default, XStream does not require any further
* 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
* <code>UTF-8</code>.
* <p/>
* <b>Note</b> that 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.
* 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
* <code>UTF-8</code>. <p/> <b>Note</b> that 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 Arjen Poutsma
@ -79,7 +76,7 @@ import org.springframework.xml.stream.XmlEventStreamReader;
* @see #DEFAULT_ENCODING
* @see #setAliases(Map)
* @see #setConverters(ConverterMatcher[])
* @since 1.0.0
* @since 3.0
*/
public class XStreamMarshaller extends AbstractMarshaller {
@ -130,8 +127,7 @@ public class XStreamMarshaller extends AbstractMarshaller {
}
/**
* Sets the classes supported by this marshaller. If this property is empty (the default), all classes are
* supported.
* Sets the classes supported by this marshaller. If this property is empty (the default), all classes are supported.
*
* @see #supports(Class)
*/
@ -204,15 +200,15 @@ public class XStreamMarshaller extends AbstractMarshaller {
* @see XStream#useAttributeFor(Class)
*/
public void setUseAttributeForTypes(Class[] types) {
for (int i = 0; i < types.length; i++) {
getXStream().useAttributeFor(types[i]);
for (Class type : types) {
getXStream().useAttributeFor(type);
}
}
/**
* Sets the types to use XML attributes for. The given map can contain either <code>&lt;String, Class&gt;</code>
* pairs, in which case {@link XStream#useAttributeFor(String,Class)} is called, or <code>&lt;Class,
* String&gt;</code> pairs, which results in {@link XStream#useAttributeFor(Class,String)}.
* Sets the types to use XML attributes for. The given map can contain either <code>&lt;String, Class&gt;</code> pairs,
* in which case {@link XStream#useAttributeFor(String,Class)} is called, or <code>&lt;Class, String&gt;</code> pairs,
* which results in {@link XStream#useAttributeFor(Class,String)}.
*/
public void setUseAttributeFor(Map attributes) {
for (Iterator iterator = attributes.entrySet().iterator(); iterator.hasNext();) {
@ -240,8 +236,8 @@ public class XStreamMarshaller extends AbstractMarshaller {
}
/**
* 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).
* 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)
*/
@ -295,19 +291,39 @@ public class XStreamMarshaller extends AbstractMarshaller {
// add each omitted field for the current type
String fieldsString = (String) entry.getValue();
String[] fields = StringUtils.commaDelimitedListToStringArray(fieldsString);
for (int i = 0; i < fields.length; i++) {
addOmittedField(type, fields[i]);
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) {
Assert.notNull(annotatedClass, "'annotatedClass' must not be null");
getXStream().processAnnotations(annotatedClass);
}
/**
* Sets annotated classes, for which aliases 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 setAnnotatedClasses(Class<?>[] annotatedClasses) {
Assert.notEmpty(annotatedClasses, "'annotatedClasses' must not be empty");
getXStream().processAnnotations(annotatedClasses);
}
public boolean supports(Class clazz) {
if (ObjectUtils.isEmpty(supportedClasses)) {
return true;
}
else {
for (int i = 0; i < supportedClasses.length; i++) {
if (supportedClasses[i].isAssignableFrom(clazz)) {
for (Class supportedClass : supportedClasses) {
if (supportedClass.isAssignableFrom(clazz)) {
return true;
}
}
@ -317,13 +333,11 @@ 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.
* 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>)
* @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)
*/
@ -365,7 +379,7 @@ public class XStreamMarshaller extends AbstractMarshaller {
@Override
protected void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter) throws XmlMappingException {
ContentHandler contentHandler = new StaxEventContentHandler(eventWriter);
ContentHandler contentHandler = StaxUtils.createContentHandler(eventWriter);
marshalSaxHandlers(graph, contentHandler, null);
}
@ -434,7 +448,7 @@ public class XStreamMarshaller extends AbstractMarshaller {
@Override
protected Object unmarshalXmlEventReader(XMLEventReader eventReader) throws XmlMappingException {
try {
XMLStreamReader streamReader = new XmlEventStreamReader(eventReader);
XMLStreamReader streamReader = StaxUtils.createEventStreamReader(eventReader);
return unmarshalXmlStreamReader(streamReader);
}
catch (XMLStreamException ex) {
@ -469,5 +483,4 @@ public class XStreamMarshaller extends AbstractMarshaller {
"XStreamMarshaller does not support unmarshalling using SAX XMLReaders");
}
}

View File

@ -19,13 +19,14 @@ 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 1.0.0
* @since 3.0
*/
public class XStreamMarshallingFailureException extends MarshallingFailureException {

View File

@ -23,7 +23,7 @@ import org.springframework.oxm.UncategorizedXmlMappingException;
* distinguished further.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public class XStreamSystemException extends UncategorizedXmlMappingException {

View File

@ -21,13 +21,14 @@ 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 1.0.0
* @since 3.0
*/
public class XStreamUnmarshallingFailureException extends UnmarshallingFailureException {

View File

@ -19,26 +19,25 @@ 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.XmlMappingException;
/**
* Generic utility methods for working with XStream. Mainly for internal use within the framework.
*
* @author Arjen Poutsma
* @since 1.0.0
* @since 3.0
*/
public abstract class XStreamUtils {
/**
* Converts 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.
* 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>)
* @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 convertXStreamException(Exception ex, boolean marshalling) {

View File

@ -1 +1 @@
http\://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd=/org/springframework/oxm/config/spring-oxm-1.5.xsd
http\://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd=/org/springframework/oxm/config/spring-oxm-3.0.xsd

View File

@ -14,35 +14,6 @@
</xsd:documentation>
</xsd:annotation>
<xsd:element name="jaxb1-marshaller">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation source="java:org.springframework.oxm.jaxb.Jaxb1Marshaller">
Defines a JAXB1 Marshaller.
</xsd:documentation>
<xsd:appinfo>
<tool:annotation>
<tool:exports type="org.springframework.oxm.jaxb.Jaxb1Marshaller"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
<xsd:complexContent>
<xsd:extension base="beans:identifiedType">
<xsd:attribute name="contextPath" type="xsd:string" use="required">
<xsd:annotation>
<xsd:documentation>The JAXB Context path</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="validating" type="xsd:boolean" default="false">
<xsd:annotation>
<xsd:documentation>Whether incoming XML should be validated.</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="jaxb2-marshaller">
<xsd:complexType>
<xsd:annotation>

View File

@ -22,20 +22,23 @@ import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stream.StreamResult;
import org.custommonkey.xmlunit.XMLTestCase;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.springframework.xml.transform.StaxResult;
import org.springframework.util.xml.StaxUtils;
public abstract class AbstractMarshallerTestCase extends XMLTestCase {
public abstract class AbstractMarshallerTestCase {
protected Marshaller marshaller;
@ -45,7 +48,8 @@ public abstract class AbstractMarshallerTestCase extends XMLTestCase {
"<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" +
"<tns:flight><tns:number>42</tns:number></tns:flight></tns:flights>";
protected final void setUp() throws Exception {
@Before
public final void setUp() throws Exception {
marshaller = createMarshaller();
flights = createFlights();
XMLUnit.setIgnoreWhitespace(true);
@ -55,7 +59,8 @@ public abstract class AbstractMarshallerTestCase extends XMLTestCase {
protected abstract Object createFlights();
public void testMarshalDOMResult() throws Exception {
@Test
public void marshalDOMResult() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
@ -77,14 +82,16 @@ public abstract class AbstractMarshallerTestCase extends XMLTestCase {
assertXMLEqual("Marshaller writes invalid DOMResult", expected, result);
}
public void testMarshalStreamResultWriter() throws Exception {
@Test
public void marshalStreamResultWriter() throws Exception {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
marshaller.marshal(flights, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStreamResultOutputStream() throws Exception {
@Test
public void marshalStreamResultOutputStream() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult result = new StreamResult(os);
marshaller.marshal(flights, result);
@ -92,25 +99,28 @@ public abstract class AbstractMarshallerTestCase extends XMLTestCase {
new String(os.toByteArray(), "UTF-8"));
}
public void testMarshalStaxResultStreamWriter() throws Exception {
@Test
public void marshalStaxResultStreamWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
StaxResult result = new StaxResult(streamWriter);
Result result = StaxUtils.createStaxResult(streamWriter);
marshaller.marshal(flights, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStaxResultEventWriter() throws Exception {
@Test
public void marshalStaxResultEventWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
StaxResult result = new StaxResult(eventWriter);
Result result = StaxUtils.createStaxResult(eventWriter);
marshaller.marshal(flights, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalJaxp14StaxResultStreamWriter() throws Exception {
@Test
public void marshalJaxp14StaxResultStreamWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
@ -119,7 +129,8 @@ public abstract class AbstractMarshallerTestCase extends XMLTestCase {
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalJaxp14StaxResultEventWriter() throws Exception {
@Test
public void marshalJaxp14StaxResultEventWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);

View File

@ -23,12 +23,15 @@ import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
@ -36,9 +39,9 @@ import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.xml.transform.StaxSource;
import org.springframework.util.xml.StaxUtils;
public abstract class AbstractUnmarshallerTestCase extends TestCase {
public abstract class AbstractUnmarshallerTestCase {
protected Unmarshaller unmarshaller;
@ -46,7 +49,8 @@ public abstract class AbstractUnmarshallerTestCase extends TestCase {
"<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" +
"<tns:flight><tns:number>42</tns:number></tns:flight></tns:flights>";
protected final void setUp() throws Exception {
@Before
public final void setUp() throws Exception {
unmarshaller = createUnmarshaller();
}
@ -56,7 +60,8 @@ public abstract class AbstractUnmarshallerTestCase extends TestCase {
protected abstract void testFlight(Object o);
public void testUnmarshalDomSource() throws Exception {
@Test
public void unmarshalDomSource() throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.newDocument();
Element flightsElement = document.createElementNS("http://samples.springframework.org/flight", "tns:flights");
@ -72,42 +77,48 @@ public abstract class AbstractUnmarshallerTestCase extends TestCase {
testFlights(flights);
}
public void testUnmarshalStreamSourceReader() throws Exception {
@Test
public void unmarshalStreamSourceReader() throws Exception {
StreamSource source = new StreamSource(new StringReader(INPUT_STRING));
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalStreamSourceInputStream() throws Exception {
@Test
public void unmarshalStreamSourceInputStream() throws Exception {
StreamSource source = new StreamSource(new ByteArrayInputStream(INPUT_STRING.getBytes("UTF-8")));
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalSAXSource() throws Exception {
@Test
public void unmarshalSAXSource() throws Exception {
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXSource source = new SAXSource(reader, new InputSource(new StringReader(INPUT_STRING)));
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalStaxSourceXmlStreamReader() throws Exception {
@Test
public void unmarshalStaxSourceXmlStreamReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
StaxSource source = new StaxSource(streamReader);
Source source = StaxUtils.createStaxSource(streamReader);
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalStaxSourceXmlEventReader() throws Exception {
@Test
public void unmarshalStaxSourceXmlEventReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_STRING));
StaxSource source = new StaxSource(eventReader);
Source source = StaxUtils.createStaxSource(eventReader);
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalJaxp14StaxSourceXmlStreamReader() throws Exception {
@Test
public void unmarshalJaxp14StaxSourceXmlStreamReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
StAXSource source = new StAXSource(streamReader);
@ -115,7 +126,8 @@ public abstract class AbstractUnmarshallerTestCase extends TestCase {
testFlights(flights);
}
public void testUnmarshalJaxp14StaxSourceXmlEventReader() throws Exception {
@Test
public void unmarshalJaxp14StaxSourceXmlEventReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_STRING));
StAXSource source = new StAXSource(eventReader);
@ -123,7 +135,8 @@ public abstract class AbstractUnmarshallerTestCase extends TestCase {
testFlights(flights);
}
public void testUnmarshalPartialStaxSourceXmlStreamReader() throws Exception {
@Test
public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
streamReader.nextTag(); // skip to flights
@ -132,7 +145,7 @@ public abstract class AbstractUnmarshallerTestCase extends TestCase {
streamReader.nextTag(); // skip to flight
assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flight"),
streamReader.getName());
StaxSource source = new StaxSource(streamReader);
Source source = StaxUtils.createStaxSource(streamReader);
Object flight = unmarshaller.unmarshal(source);
testFlight(flight);
}

View File

@ -17,11 +17,15 @@ package org.springframework.oxm.castor;
import javax.xml.transform.sax.SAXResult;
import org.easymock.MockControl;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.AbstractMarshallerTestCase;
import org.springframework.oxm.Marshaller;
import org.xml.sax.ContentHandler;
public class CastorMarshallerTest extends AbstractMarshallerTestCase {
@ -43,32 +47,32 @@ public class CastorMarshallerTest extends AbstractMarshallerTestCase {
return flights;
}
public void testMarshalSaxResult() throws Exception {
MockControl handlerControl = MockControl.createControl(ContentHandler.class);
ContentHandler handlerMock = (ContentHandler) handlerControl.getMock();
@Test
public void marshalSaxResult() throws Exception {
ContentHandler handlerMock = createMock(ContentHandler.class);
handlerMock.startDocument();
handlerMock.startPrefixMapping("tns", "http://samples.springframework.org/flight");
handlerMock.startElement("http://samples.springframework.org/flight", "flights", "tns:flights", null);
handlerControl.setMatcher(MockControl.ALWAYS_MATCHER);
handlerMock.startElement("http://samples.springframework.org/flight", "flight", "tns:flight", null);
handlerControl.setMatcher(MockControl.ALWAYS_MATCHER);
handlerMock.startElement("http://samples.springframework.org/flight", "number", "tns:number", null);
handlerControl.setMatcher(MockControl.ALWAYS_MATCHER);
handlerMock.characters(new char[]{'4', '2'}, 0, 2);
handlerControl.setMatcher(MockControl.ARRAY_MATCHER);
handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("tns:flights"),
isA(Attributes.class));
handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("tns:flight"),
isA(Attributes.class));
handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("tns:number"),
isA(Attributes.class));
handlerMock.characters(aryEq(new char[]{'4', '2'}), eq(0), eq(2));
handlerMock.endElement("http://samples.springframework.org/flight", "number", "tns:number");
handlerMock.endElement("http://samples.springframework.org/flight", "flight", "tns:flight");
handlerMock.endElement("http://samples.springframework.org/flight", "flights", "tns:flights");
handlerMock.endPrefixMapping("tns");
handlerMock.endDocument();
handlerControl.replay();
replay(handlerMock);
SAXResult result = new SAXResult(handlerMock);
marshaller.marshal(flights, result);
handlerControl.verify();
verify(handlerMock);
}
public void testSupports() throws Exception {
@Test
public void supports() throws Exception {
assertTrue("CastorMarshaller does not support Flights", marshaller.supports(Flights.class));
assertTrue("CastorMarshaller does not support Flight", marshaller.supports(Flight.class));
}

View File

@ -19,6 +19,10 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamSource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.AbstractUnmarshallerTestCase;
import org.springframework.oxm.Unmarshaller;
@ -49,7 +53,8 @@ public class CastorUnmarshallerTest extends AbstractUnmarshallerTestCase {
return marshaller;
}
public void testUnmarshalTargetClass() throws Exception {
@Test
public void unmarshalTargetClass() throws Exception {
CastorMarshaller unmarshaller = new CastorMarshaller();
unmarshaller.setTargetClass(Flights.class);
unmarshaller.afterPropertiesSet();
@ -58,17 +63,12 @@ public class CastorUnmarshallerTest extends AbstractUnmarshallerTestCase {
testFlights(flights);
}
@Test(expected = IllegalArgumentException.class)
public void testSetBothTargetClassAndMapping() throws IOException {
try {
CastorMarshaller marshaller = new CastorMarshaller();
marshaller.setMappingLocation(new ClassPathResource("mapping.xml", CastorMarshaller.class));
marshaller.setTargetClass(getClass());
marshaller.afterPropertiesSet();
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// expected
}
}
}

View File

@ -1,41 +0,0 @@
/*
* Copyright ${YEAR} 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.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import junit.framework.TestCase;
public class Jaxb2OxmNamespaceHandlerTest extends TestCase {
private ApplicationContext applicationContext;
protected void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("jaxb2OxmNamespaceHandlerTest.xml", getClass());
}
public void testContextPathMarshaller() throws Exception {
applicationContext.getBean("contextPathMarshaller", Jaxb2Marshaller.class);
}
public void testClassesToBeBoundMarshaller() throws Exception {
applicationContext.getBean("classesMarshaller", Jaxb2Marshaller.class);
}
}

View File

@ -16,37 +16,50 @@
package org.springframework.oxm.config;
import org.apache.xmlbeans.XmlOptions;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.jaxb.Jaxb1Marshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.oxm.jibx.JibxMarshaller;
import org.springframework.oxm.xmlbeans.XmlBeansMarshaller;
import junit.framework.TestCase;
import org.apache.xmlbeans.XmlOptions;
public class OxmNamespaceHandlerTest extends TestCase {
public class OxmNamespaceHandlerTest {
private ApplicationContext applicationContext;
protected void setUp() throws Exception {
@Before
public void createAppContext() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("oxmNamespaceHandlerTest.xml", getClass());
}
public void testJaxb1Marshaller() throws Exception {
applicationContext.getBean("jaxb1Marshaller", Jaxb1Marshaller.class);
}
public void testJibxMarshaller() throws Exception {
@Test
@Ignore
public void jibxMarshaller() throws Exception {
applicationContext.getBean("jibxMarshaller", JibxMarshaller.class);
}
public void testXmlBeansMarshaller() throws Exception {
XmlBeansMarshaller marshaller =
(XmlBeansMarshaller) applicationContext.getBean("xmlBeansMarshaller", XmlBeansMarshaller.class);
@Test
public void xmlBeansMarshaller() throws Exception {
XmlBeansMarshaller marshaller = applicationContext.getBean("xmlBeansMarshaller", XmlBeansMarshaller.class);
XmlOptions options = marshaller.getXmlOptions();
assertNotNull("Options not set", options);
assertTrue("option not set", options.hasOption("SAVE_PRETTY_PRINT"));
assertEquals("option not set", "true", options.get("SAVE_PRETTY_PRINT"));
}
@Test
public void jaxb2ContextPathMarshaller() throws Exception {
applicationContext.getBean("contextPathMarshaller", Jaxb2Marshaller.class);
}
@Test
public void jaxb2ClassesToBeBoundMarshaller() throws Exception {
applicationContext.getBean("classesMarshaller", Jaxb2Marshaller.class);
}
}

View File

@ -0,0 +1,47 @@
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.3-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.01.08 at 12:41:36 PM CET
//
package org.springframework.oxm.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for flightType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="flightType">
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="number" type="{http://www.w3.org/2001/XMLSchema}long"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "flightType", propOrder = {"number"})
public class FlightType {
protected long number;
/** Gets the value of the number property. */
public long getNumber() {
return number;
}
/** Sets the value of the number property. */
public void setNumber(long value) {
this.number = value;
}
}

View File

@ -0,0 +1,66 @@
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.3-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.01.08 at 12:41:36 PM CET
//
package org.springframework.oxm.jaxb;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="flight" type="{http://samples.springframework.org/flight}flightType"
* maxOccurs="unbounded"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"flight"})
@XmlRootElement(name = "flights")
public class Flights {
@XmlElement(required = true)
protected List<FlightType> flight;
/**
* Gets the value of the flight property.
*
* <p> This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make
* to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for
* the flight property.
*
* <p> For example, to add a new item, do as follows:
* <pre>
* getFlight().add(newItem);
* </pre>
*
*
* <p> Objects of the following type(s) are allowed in the list {@link FlightType }
*/
public List<FlightType> getFlight() {
if (flight == null) {
flight = new ArrayList<FlightType>();
}
return this.flight;
}
}

View File

@ -1,84 +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.util.Collections;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.jaxb1.FlightType;
import org.springframework.oxm.jaxb1.Flights;
import org.springframework.oxm.jaxb1.FlightsType;
import org.springframework.oxm.jaxb1.impl.FlightTypeImpl;
import org.springframework.oxm.jaxb1.impl.FlightsImpl;
public class Jaxb1MarshallerTest extends AbstractJaxbMarshallerTestCase {
private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb1";
@Override
protected final Marshaller createMarshaller() throws Exception {
Jaxb1Marshaller marshaller = new Jaxb1Marshaller();
marshaller.setContextPaths(new String[]{CONTEXT_PATH});
marshaller.afterPropertiesSet();
return marshaller;
}
@Override
protected Object createFlights() {
FlightType flight = new FlightTypeImpl();
flight.setNumber(42L);
Flights flights = new FlightsImpl();
flights.getFlight().add(flight);
return flights;
}
public void testProperties() throws Exception {
Jaxb1Marshaller marshaller = new Jaxb1Marshaller();
marshaller.setContextPath(CONTEXT_PATH);
marshaller.setMarshallerProperties(
Collections.singletonMap(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE));
marshaller.afterPropertiesSet();
}
public void testNoContextPath() throws Exception {
try {
Jaxb1Marshaller marshaller = new Jaxb1Marshaller();
marshaller.afterPropertiesSet();
fail("Should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e) {
}
}
public void testInvalidContextPath() throws Exception {
try {
Jaxb1Marshaller marshaller = new Jaxb1Marshaller();
marshaller.setContextPath("ab");
marshaller.afterPropertiesSet();
fail("Should have thrown an XmlMappingException");
}
catch (XmlMappingException ex) {
}
}
public void testSupports() throws Exception {
assertTrue("Jaxb1Marshaller does not support Flights", marshaller.supports(Flights.class));
assertFalse("Jaxb1Marshaller supports FlightsType", marshaller.supports(FlightsType.class));
}
}

View File

@ -1,49 +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 org.springframework.oxm.AbstractUnmarshallerTestCase;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.jaxb1.FlightType;
import org.springframework.oxm.jaxb1.Flights;
public class Jaxb1UnmarshallerTest extends AbstractUnmarshallerTestCase {
@Override
protected Unmarshaller createUnmarshaller() throws Exception {
Jaxb1Marshaller marshaller = new Jaxb1Marshaller();
marshaller.setContextPath("org.springframework.oxm.jaxb1");
marshaller.setValidating(true);
marshaller.afterPropertiesSet();
return marshaller;
}
@Override
protected void testFlights(Object o) {
Flights flights = (Flights) o;
assertNotNull("Flights is null", flights);
assertEquals("Invalid amount of flight elements", 1, flights.getFlight().size());
testFlight(flights.getFlight().get(0));
}
@Override
protected void testFlight(Object o) {
FlightType flight = (FlightType) o;
assertNotNull("Flight is null", flight);
assertEquals("Number is invalid", 42L, flight.getNumber());
}
}

View File

@ -20,7 +20,6 @@ import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
@ -47,8 +46,12 @@ import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stream.StreamResult;
import org.custommonkey.xmlunit.XMLTestCase;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
@ -59,17 +62,13 @@ import org.xml.sax.Locator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.jaxb2.FlightType;
import org.springframework.oxm.jaxb2.Flights;
import org.springframework.oxm.jaxb2.ObjectFactory;
import org.springframework.oxm.mime.MimeContainer;
import org.springframework.util.FileCopyUtils;
import org.springframework.xml.transform.StaxResult;
import org.springframework.xml.transform.StringResult;
import org.springframework.util.xml.StaxUtils;
public class Jaxb2MarshallerTest extends XMLTestCase {
public class Jaxb2MarshallerTest {
private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb2";
private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb";
private static final String EXPECTED_STRING =
"<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" +
@ -79,7 +78,8 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
private Flights flights;
protected void setUp() throws Exception {
@Before
public void createMarshaller() throws Exception {
marshaller = new Jaxb2Marshaller();
marshaller.setContextPath(CONTEXT_PATH);
marshaller.afterPropertiesSet();
@ -89,7 +89,8 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
flights.getFlight().add(flight);
}
public void testMarshalDOMResult() throws Exception {
@Test
public void marshalDOMResult() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document = builder.newDocument();
@ -107,14 +108,16 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
assertXMLEqual("Marshaller writes invalid DOMResult", expected, document);
}
public void testMarshalStreamResultWriter() throws Exception {
@Test
public void marshalStreamResultWriter() throws Exception {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
marshaller.marshal(flights, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStreamResultOutputStream() throws Exception {
@Test
public void marshalStreamResultOutputStream() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult result = new StreamResult(os);
marshaller.marshal(flights, result);
@ -122,25 +125,28 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
new String(os.toByteArray(), "UTF-8"));
}
public void testMarshalStaxResultXMLStreamWriter() throws Exception {
@Test
public void marshalStaxResultXMLStreamWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
StaxResult result = new StaxResult(streamWriter);
Result result = StaxUtils.createStaxResult(streamWriter);
marshaller.marshal(flights, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStaxResultXMLEventWriter() throws Exception {
@Test
public void marshalStaxResultXMLEventWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
StaxResult result = new StaxResult(eventWriter);
Result result = StaxUtils.createStaxResult(eventWriter);
marshaller.marshal(flights, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStaxResultXMLStreamWriterJaxp14() throws Exception {
@Test
public void marshalStaxResultXMLStreamWriterJaxp14() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
@ -149,7 +155,8 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStaxResultXMLEventWriterJaxp14() throws Exception {
@Test
public void marshalStaxResultXMLEventWriterJaxp14() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
@ -158,7 +165,8 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testProperties() throws Exception {
@Test
public void properties() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath(CONTEXT_PATH);
marshaller.setMarshallerProperties(
@ -166,43 +174,31 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
marshaller.afterPropertiesSet();
}
public void testNoContextPathOrClassesToBeBound() throws Exception {
try {
@Test(expected = IllegalArgumentException.class)
public void noContextPathOrClassesToBeBound() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.afterPropertiesSet();
fail("Should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e) {
}
}
@Test(expected = XmlMappingException.class)
public void testInvalidContextPath() throws Exception {
try {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("ab");
marshaller.afterPropertiesSet();
fail("Should have thrown an XmlMappingException");
}
catch (XmlMappingException ex) {
}
}
public void testMarshalInvalidClass() throws Exception {
@Test(expected = XmlMappingException.class)
public void marshalInvalidClass() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[]{FlightType.class});
marshaller.afterPropertiesSet();
Result result = new StreamResult(new StringWriter());
Flights flights = new Flights();
try {
marshaller.marshal(flights, result);
fail("Should have thrown an MarshallingFailureException");
}
catch (XmlMappingException ex) {
// expected
}
}
public void testMarshalSaxResult() throws Exception {
@Test
public void marshalSaxResult() throws Exception {
ContentHandler handlerMock = createStrictMock(ContentHandler.class);
handlerMock.setDocumentLocator(isA(Locator.class));
handlerMock.startDocument();
@ -226,7 +222,8 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
verify(handlerMock);
}
public void testSupportsContextPath() throws Exception {
@Test
public void supportsContextPath() throws Exception {
Method createFlights = ObjectFactory.class.getDeclaredMethod("createFlights");
assertTrue("Jaxb2Marshaller does not support Flights",
marshaller.supports(createFlights.getGenericReturnType()));
@ -239,7 +236,8 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
assertFalse("Jaxb2Marshaller supports wrong JAXBElement", marshaller.supports(testElement.getClass()));
}
public void testSupportsClassesToBeBound() throws Exception {
@Test
public void supportsClassesToBeBound() throws Exception {
marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[]{Flights.class, FlightType.class});
marshaller.afterPropertiesSet();
@ -255,30 +253,32 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
assertFalse("Jaxb2Marshaller supports wrong JAXBElement", marshaller.supports(testElement.getClass()));
}
public void testSupportsPrimitives() throws Exception {
Method primitives = getClass().getDeclaredMethod("primitives", JAXBElement.class, JAXBElement.class,
@Test
public void supportsPrimitives() throws Exception {
Method primitives = getClass()
.getDeclaredMethod("primitives", JAXBElement.class, JAXBElement.class, JAXBElement.class,
JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class);
Type[] types = primitives.getGenericParameterTypes();
for (Type type : types) {
assertTrue("Jaxb2Marshaller does not support " + type, marshaller.supports(type));
}
}
@Test
public void supportsStandards() throws Exception {
Method standards = getClass()
.getDeclaredMethod("standards", JAXBElement.class, JAXBElement.class, JAXBElement.class,
JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class,
JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class,
JAXBElement.class);
Type[] types = primitives.getGenericParameterTypes();
for (int i = 0; i < types.length; i++) {
ParameterizedType type = (ParameterizedType) types[i];
assertTrue("Jaxb2Marshaller does not support " + type, marshaller.supports(types[i]));
}
}
public void testSupportsStandards() throws Exception {
Method standards = getClass().getDeclaredMethod("standards", JAXBElement.class, JAXBElement.class,
JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class,
JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class, JAXBElement.class,
JAXBElement.class, JAXBElement.class);
Type[] types = standards.getGenericParameterTypes();
for (int i = 0; i < types.length; i++) {
ParameterizedType type = (ParameterizedType) types[i];
assertTrue("Jaxb2Marshaller does not support " + type, marshaller.supports(types[i]));
for (Type type : types) {
assertTrue("Jaxb2Marshaller does not support " + type, marshaller.supports(type));
}
}
public void testMarshalAttachments() throws Exception {
@Test
public void marshalAttachments() throws Exception {
marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[]{BinaryObject.class});
marshaller.setMtomEnabled(true);
@ -295,10 +295,10 @@ public class Jaxb2MarshallerTest extends XMLTestCase {
replay(mimeContainer);
byte[] bytes = FileCopyUtils.copyToByteArray(logo.getInputStream());
BinaryObject object = new BinaryObject(bytes, dataHandler);
Result result = new StringResult();
marshaller.marshal(object, result, mimeContainer);
StringWriter writer = new StringWriter();
marshaller.marshal(object, new StreamResult(writer), mimeContainer);
verify(mimeContainer);
assertTrue("No XML written", result.toString().length() > 0);
assertTrue("No XML written", writer.toString().length() > 0);
}
private void primitives(JAXBElement<Boolean> bool,

View File

@ -32,8 +32,10 @@ import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import junit.framework.TestCase;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
@ -43,27 +45,26 @@ import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.jaxb2.FlightType;
import org.springframework.oxm.jaxb2.Flights;
import org.springframework.oxm.mime.MimeContainer;
import org.springframework.xml.transform.StaxSource;
import org.springframework.xml.transform.StringSource;
import org.springframework.util.xml.StaxUtils;
public class Jaxb2UnmarshallerTest extends TestCase {
public class Jaxb2UnmarshallerTest {
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>";
private Jaxb2Marshaller unmarshaller;
protected void setUp() throws Exception {
@Before
public void createMarshaller() throws Exception {
unmarshaller = new Jaxb2Marshaller();
unmarshaller.setContextPath("org.springframework.oxm.jaxb2");
unmarshaller.setContextPath("org.springframework.oxm.jaxb");
unmarshaller.setSchema(new ClassPathResource("org/springframework/oxm/flight.xsd"));
unmarshaller.afterPropertiesSet();
}
public void testUnmarshalDomSource() throws Exception {
@Test
public void unmarshalDomSource() throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.newDocument();
Element flightsElement = document.createElementNS("http://samples.springframework.org/flight", "tns:flights");
@ -79,42 +80,48 @@ public class Jaxb2UnmarshallerTest extends TestCase {
testFlights(flights);
}
public void testUnmarshalStreamSourceReader() throws Exception {
@Test
public void unmarshalStreamSourceReader() throws Exception {
StreamSource source = new StreamSource(new StringReader(INPUT_STRING));
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
@Test
public void testUnmarshalStreamSourceInputStream() throws Exception {
StreamSource source = new StreamSource(new ByteArrayInputStream(INPUT_STRING.getBytes("UTF-8")));
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalSAXSource() throws Exception {
@Test
public void unmarshalSAXSource() throws Exception {
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXSource source = new SAXSource(reader, new InputSource(new StringReader(INPUT_STRING)));
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalStaxSourceXmlStreamReader() throws Exception {
@Test
public void unmarshalStaxSourceXmlStreamReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
StaxSource source = new StaxSource(streamReader);
Source source = StaxUtils.createStaxSource(streamReader);
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalStaxSourceXmlEventReader() throws Exception {
@Test
public void unmarshalStaxSourceXmlEventReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_STRING));
StaxSource source = new StaxSource(eventReader);
Source source = StaxUtils.createStaxSource(eventReader);
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}
public void testUnmarshalStaxSourceXmlStreamReaderJaxp14() throws Exception {
@Test
public void unmarshalStaxSourceXmlStreamReaderJaxp14() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
StAXSource source = new StAXSource(streamReader);
@ -122,7 +129,8 @@ public class Jaxb2UnmarshallerTest extends TestCase {
testFlights(flights);
}
public void testUnmarshalStaxSourceXmlEventReaderJaxp14() throws Exception {
@Test
public void unmarshalStaxSourceXmlEventReaderJaxp14() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_STRING));
StAXSource source = new StAXSource(eventReader);
@ -130,7 +138,8 @@ public class Jaxb2UnmarshallerTest extends TestCase {
testFlights(flights);
}
public void testMarshalAttachments() throws Exception {
@Test
public void marshalAttachments() throws Exception {
unmarshaller = new Jaxb2Marshaller();
unmarshaller.setClassesToBeBound(new Class[]{BinaryObject.class});
unmarshaller.setMtomEnabled(true);
@ -142,11 +151,9 @@ public class Jaxb2UnmarshallerTest extends TestCase {
expect(mimeContainer.isXopPackage()).andReturn(true);
expect(mimeContainer.getAttachment(
"<6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws>"))
.andReturn(dataHandler);
"<6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws>")).andReturn(dataHandler);
expect(mimeContainer.getAttachment(
"<99bd1592-0521-41a2-9688-a8bfb40192fb@http://springframework.org/spring-ws>"))
.andReturn(dataHandler);
"<99bd1592-0521-41a2-9688-a8bfb40192fb@http://springframework.org/spring-ws>")).andReturn(dataHandler);
expect(mimeContainer.getAttachment("696cfb9a-4d2d-402f-bb5c-59fa69e7f0b3@spring-ws.png"))
.andReturn(dataHandler);
replay(mimeContainer);
@ -158,8 +165,8 @@ public class Jaxb2UnmarshallerTest extends TestCase {
"<swaDataHandler>696cfb9a-4d2d-402f-bb5c-59fa69e7f0b3@spring-ws.png</swaDataHandler>" +
"</binaryObject>";
Source source = new StringSource(content);
Object result = unmarshaller.unmarshal(source, mimeContainer);
StringReader reader = new StringReader(content);
Object result = unmarshaller.unmarshal(new StreamSource(reader), mimeContainer);
assertTrue("Result is not a BinaryObject", result instanceof BinaryObject);
verify(mimeContainer);
BinaryObject object = (BinaryObject) result;
@ -181,12 +188,13 @@ public class Jaxb2UnmarshallerTest extends TestCase {
assertEquals("Number is invalid", 42L, flight.getNumber());
}
public void testUnmarshalPartialStaxSourceXmlStreamReader() throws Exception {
@Test
public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
streamReader.nextTag(); // skip to flights
streamReader.nextTag(); // skip to flight
StaxSource source = new StaxSource(streamReader);
Source source = StaxUtils.createStaxSource(streamReader);
JAXBElement<FlightType> element = (JAXBElement<FlightType>) unmarshaller.unmarshal(source);
FlightType flight = element.getValue();
testFlight(flight);

View File

@ -0,0 +1,66 @@
/*
* 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.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.3-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.01.08 at 12:41:36 PM CET
//
package org.springframework.oxm.jaxb;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each Java content interface and Java element interface generated in the
* org.springframework.oxm.jaxb package. <p>An ObjectFactory allows you to programatically construct new instances of
* the Java representation for XML content. The Java representation of XML content can consist of schema derived
* interfaces and classes representing the binding of schema type definitions, element declarations and model groups.
* Factory methods for each of these are provided in this class.
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _Flight_QNAME = new QName("http://samples.springframework.org/flight", "flight");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
* org.springframework.oxm.jaxb
*/
public ObjectFactory() {
}
/** Create an instance of {@link FlightType } */
public FlightType createFlightType() {
return new FlightType();
}
/** Create an instance of {@link Flights } */
public Flights createFlights() {
return new Flights();
}
/** Create an instance of {@link JAXBElement }{@code <}{@link FlightType }{@code >}} */
@XmlElementDecl(namespace = "http://samples.springframework.org/flight", name = "flight")
public JAXBElement<FlightType> createFlight(FlightType value) {
return new JAXBElement<FlightType>(_Flight_QNAME, FlightType.class, null, value);
}
}

View File

@ -0,0 +1,25 @@
/*
* 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.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.3-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.01.08 at 12:41:36 PM CET
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://samples.springframework.org/flight",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.springframework.oxm.jaxb;

View File

@ -16,12 +16,20 @@
package org.springframework.oxm.jibx;
import java.io.StringWriter;
import javax.xml.transform.stream.StreamResult;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import org.custommonkey.xmlunit.XMLUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.oxm.AbstractMarshallerTestCase;
import org.springframework.oxm.Marshaller;
import org.springframework.xml.transform.StringResult;
@Ignore
public class JibxMarshallerTest extends AbstractMarshallerTestCase {
@Override
@ -41,36 +49,35 @@ public class JibxMarshallerTest extends AbstractMarshallerTestCase {
return flights;
}
public void testAfterPropertiesSetNoContextPath() throws Exception {
try {
@Test(expected = IllegalArgumentException.class)
public void afterPropertiesSetNoContextPath() throws Exception {
JibxMarshaller marshaller = new JibxMarshaller();
marshaller.afterPropertiesSet();
fail("Should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e) {
}
}
public void testIndentation() throws Exception {
@Test
public void indentation() throws Exception {
((JibxMarshaller) marshaller).setIndent(4);
StringResult result = new StringResult();
marshaller.marshal(flights, result);
StringWriter writer = new StringWriter();
marshaller.marshal(flights, new StreamResult(writer));
XMLUnit.setIgnoreWhitespace(false);
String expected = "<?xml version=\"1.0\"?>\n" +
"<flights xmlns=\"http://samples.springframework.org/flight\">\n" + " <flight>\n" +
" <number>42</number>\n" + " </flight>\n" + "</flights>";
assertXMLEqual(expected, result.toString());
String expected =
"<?xml version=\"1.0\"?>\n" + "<flights xmlns=\"http://samples.springframework.org/flight\">\n" +
" <flight>\n" + " <number>42</number>\n" + " </flight>\n" + "</flights>";
assertXMLEqual(expected, writer.toString());
}
public void testEncodingAndStandalone() throws Exception {
@Test
public void encodingAndStandalone() throws Exception {
((JibxMarshaller) marshaller).setEncoding("ISO-8859-1");
((JibxMarshaller) marshaller).setStandalone(Boolean.TRUE);
StringResult result = new StringResult();
marshaller.marshal(flights, result);
StringWriter writer = new StringWriter();
marshaller.marshal(flights, new StreamResult(writer));
assertTrue("Encoding and standalone not set",
result.toString().startsWith("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>"));
writer.toString().startsWith("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>"));
}
@Test
public void testSupports() throws Exception {
assertTrue("JibxMarshaller does not support Flights", marshaller.supports(Flights.class));
assertTrue("JibxMarshaller does not support FlightType", marshaller.supports(FlightType.class));

View File

@ -15,9 +15,14 @@
*/
package org.springframework.oxm.jibx;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Ignore;
import org.springframework.oxm.AbstractUnmarshallerTestCase;
import org.springframework.oxm.Unmarshaller;
@Ignore
public class JibxUnmarshallerTest extends AbstractUnmarshallerTestCase {
@Override
@ -44,7 +49,8 @@ public class JibxUnmarshallerTest extends AbstractUnmarshallerTestCase {
}
@Override
public void testUnmarshalPartialStaxSourceXmlStreamReader() throws Exception {
@Ignore
public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception {
// JiBX does not support reading XML fragments, hence the override here
}
}

View File

@ -1,156 +0,0 @@
/*
* Copyright 2007 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.support;
import javax.jms.BytesMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
public class MarshallingMessageConverterTest extends TestCase {
private MarshallingMessageConverter converter;
private MockControl marshallerControl;
private Marshaller marshallerMock;
private MockControl unmarshallerControl;
private Unmarshaller unmarshallerMock;
private MockControl sessionControl;
private Session sessionMock;
protected void setUp() throws Exception {
marshallerControl = MockControl.createControl(Marshaller.class);
marshallerMock = (Marshaller) marshallerControl.getMock();
unmarshallerControl = MockControl.createControl(Unmarshaller.class);
unmarshallerMock = (Unmarshaller) unmarshallerControl.getMock();
converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock);
sessionControl = MockControl.createControl(Session.class);
sessionMock = (Session) sessionControl.getMock();
}
public void testToBytesMessage() throws Exception {
MockControl bytesMessageControl = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessageMock = (BytesMessage) bytesMessageControl.getMock();
Object toBeMarshalled = new Object();
sessionControl.expectAndReturn(sessionMock.createBytesMessage(), bytesMessageMock);
marshallerMock.marshal(toBeMarshalled, new StringResult());
marshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
bytesMessageMock.writeBytes(new byte[0]);
bytesMessageControl.setMatcher(MockControl.ALWAYS_MATCHER);
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
bytesMessageControl.replay();
converter.toMessage(toBeMarshalled, sessionMock);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
bytesMessageControl.verify();
}
public void testFromBytesMessage() throws Exception {
MockControl bytesMessageControl = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessageMock = (BytesMessage) bytesMessageControl.getMock();
Object unmarshalled = new Object();
bytesMessageControl.expectAndReturn(bytesMessageMock.getBodyLength(), 10);
bytesMessageMock.readBytes(new byte[0]);
bytesMessageControl.setMatcher(MockControl.ALWAYS_MATCHER);
bytesMessageControl.setReturnValue(0);
unmarshallerMock.unmarshal(new StringSource(""));
unmarshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
unmarshallerControl.setReturnValue(unmarshalled);
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
bytesMessageControl.replay();
Object result = converter.fromMessage(bytesMessageMock);
assertEquals("Invalid result", result, unmarshalled);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
bytesMessageControl.verify();
}
public void testToTextMessage() throws Exception {
converter.setMarshalTo(MarshallingMessageConverter.MARSHAL_TO_TEXT_MESSAGE);
MockControl textMessageControl = MockControl.createControl(TextMessage.class);
TextMessage textMessageMock = (TextMessage) textMessageControl.getMock();
Object toBeMarshalled = new Object();
sessionControl.expectAndReturn(sessionMock.createTextMessage(""), textMessageMock);
marshallerMock.marshal(toBeMarshalled, new StringResult());
marshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
textMessageControl.replay();
converter.toMessage(toBeMarshalled, sessionMock);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
textMessageControl.verify();
}
public void testFromTextMessage() throws Exception {
MockControl textMessageControl = MockControl.createControl(TextMessage.class);
TextMessage textMessageMock = (TextMessage) textMessageControl.getMock();
Object unmarshalled = new Object();
unmarshallerMock.unmarshal(new StringSource(""));
unmarshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
unmarshallerControl.setReturnValue(unmarshalled);
textMessageControl.expectAndReturn(textMessageMock.getText(), "");
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
textMessageControl.replay();
Object result = converter.fromMessage(textMessageMock);
assertEquals("Invalid result", result, unmarshalled);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
textMessageControl.verify();
}
}

View File

@ -1,135 +0,0 @@
/*
* Copyright 2007 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.support;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamResult;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.oxm.Marshaller;
public class MarshallingViewTest extends TestCase {
private MarshallingView view;
private MockControl control;
private Marshaller marshallerMock;
protected void setUp() throws Exception {
control = MockControl.createControl(Marshaller.class);
marshallerMock = (Marshaller) control.getMock();
view = new MarshallingView(marshallerMock);
}
public void testGetContentType() {
Assert.assertEquals("Invalid content type", "application/xml", view.getContentType());
}
public void testRenderModelKey() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
view.setModelKey(modelKey);
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
control.expectAndReturn(marshallerMock.supports(Object.class), true);
marshallerMock.marshal(toBeMarshalled, new StreamResult(response.getOutputStream()));
control.setMatcher(MockControl.ALWAYS_MATCHER);
control.replay();
view.render(model, request, response);
Assert.assertEquals("Invalid content type", "application/xml", response.getContentType());
Assert.assertEquals("Invalid content length", 0, response.getContentLength());
control.verify();
}
public void testRenderModelKeyUnsupported() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
view.setModelKey(modelKey);
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
control.expectAndReturn(marshallerMock.supports(Object.class), false);
control.replay();
try {
view.render(model, request, response);
fail("ServletException expected");
}
catch (ServletException ex) {
// expected
}
control.verify();
}
public void testRenderNoModelKey() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
control.expectAndReturn(marshallerMock.supports(Object.class), true);
marshallerMock.marshal(toBeMarshalled, new StreamResult(response.getOutputStream()));
control.setMatcher(MockControl.ALWAYS_MATCHER);
control.replay();
view.render(model, request, response);
Assert.assertEquals("Invalid content type", "application/xml", response.getContentType());
Assert.assertEquals("Invalid content length", 0, response.getContentLength());
control.verify();
}
public void testRenderUnsupportedModel() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
control.expectAndReturn(marshallerMock.supports(Object.class), false);
control.replay();
try {
view.render(model, request, response);
fail("ServletException expected");
}
catch (ServletException ex) {
// expected
}
control.verify();
}
}

View File

@ -0,0 +1,180 @@
/*
* 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.
*/
/*
* An XML document type.
* Localname: flight
* Namespace: http://samples.springframework.org/flight
* Java type: org.springframework.samples.flight.FlightDocument
*
* Automatically generated - do not modify.
*/
package org.springframework.oxm.xmlbeans;
/**
* A document containing one flight(@http://samples.springframework.org/flight) element.
*
* This is a complex type.
*/
public interface FlightDocument extends org.apache.xmlbeans.XmlObject {
public static final org.apache.xmlbeans.SchemaType type =
(org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans
.typeSystemForClassLoader(FlightDocument.class.getClassLoader(),
"schemaorg_apache_xmlbeans.system.s5EF858A5E57B2761C3670716FC0A909C")
.resolveHandle("flightc6b8doctype");
/** Gets the "flight" element */
org.springframework.oxm.xmlbeans.FlightType getFlight();
/** Sets the "flight" element */
void setFlight(org.springframework.oxm.xmlbeans.FlightType flight);
/** Appends and returns a new empty "flight" element */
org.springframework.oxm.xmlbeans.FlightType addNewFlight();
/** A factory class with static methods for creating instances of this type. */
public static final class Factory {
public static org.springframework.oxm.xmlbeans.FlightDocument newInstance() {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.newInstance(type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument newInstance(org.apache.xmlbeans.XmlOptions options) {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.newInstance(type, options);
}
/** @param xmlAsString the string value to parse */
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.lang.String xmlAsString)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xmlAsString, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.lang.String xmlAsString,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xmlAsString, type, options);
}
/** @param file the file from which to load an xml document */
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.io.File file)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(file, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.io.File file,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(file, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.net.URL u)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(u, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.net.URL u,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(u, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.io.InputStream is)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(is, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.io.InputStream is,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(is, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.io.Reader r)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(r, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(java.io.Reader r,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(r, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(javax.xml.stream.XMLStreamReader sr)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(sr, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(javax.xml.stream.XMLStreamReader sr,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(sr, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(org.w3c.dom.Node node)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(node, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightDocument parse(org.w3c.dom.Node node,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(node, type, options);
}
/** @deprecated {@link XMLInputStream} */
public static org.springframework.oxm.xmlbeans.FlightDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xis, type, null);
}
/** @deprecated {@link XMLInputStream} */
public static org.springframework.oxm.xmlbeans.FlightDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis,
org.apache.xmlbeans.XmlOptions options)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (org.springframework.oxm.xmlbeans.FlightDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xis, type, options);
}
/** @deprecated {@link XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream(xis, type, null);
}
/** @deprecated {@link XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis,
org.apache.xmlbeans.XmlOptions options)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream(xis, type, options);
}
private Factory() {
} // No instance of this class allowed
}
}

View File

@ -0,0 +1,182 @@
/*
* 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.
*/
/*
* XML Type: flightType
* Namespace: http://samples.springframework.org/flight
* Java type: org.springframework.samples.flight.FlightType
*
* Automatically generated - do not modify.
*/
package org.springframework.oxm.xmlbeans;
/**
* An XML flightType(@http://samples.springframework.org/flight).
*
* This is a complex type.
*/
public interface FlightType extends org.apache.xmlbeans.XmlObject {
public static final org.apache.xmlbeans.SchemaType type =
(org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans
.typeSystemForClassLoader(FlightType.class.getClassLoader(),
"schemaorg_apache_xmlbeans.system.s5EF858A5E57B2761C3670716FC0A909C")
.resolveHandle("flighttype4702type");
/** Gets the "number" element */
long getNumber();
/** Gets (as xml) the "number" element */
org.apache.xmlbeans.XmlLong xgetNumber();
/** Sets the "number" element */
void setNumber(long number);
/** Sets (as xml) the "number" element */
void xsetNumber(org.apache.xmlbeans.XmlLong number);
/** A factory class with static methods for creating instances of this type. */
public static final class Factory {
public static org.springframework.oxm.xmlbeans.FlightType newInstance() {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.newInstance(type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.newInstance(type, options);
}
/** @param xmlAsString the string value to parse */
public static org.springframework.oxm.xmlbeans.FlightType parse(java.lang.String xmlAsString)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xmlAsString, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.lang.String xmlAsString,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xmlAsString, type, options);
}
/** @param file the file from which to load an xml document */
public static org.springframework.oxm.xmlbeans.FlightType parse(java.io.File file)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(file, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.io.File file,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(file, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.net.URL u)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(u, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.net.URL u,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(u, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.io.InputStream is)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(is, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.io.InputStream is,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(is, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.io.Reader r)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(r, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(java.io.Reader r,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(r, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(javax.xml.stream.XMLStreamReader sr)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(sr, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(javax.xml.stream.XMLStreamReader sr,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(sr, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(org.w3c.dom.Node node)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(node, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightType parse(org.w3c.dom.Node node,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(node, type, options);
}
/** @deprecated {@link XMLInputStream} */
public static org.springframework.oxm.xmlbeans.FlightType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xis, type, null);
}
/** @deprecated {@link XMLInputStream} */
public static org.springframework.oxm.xmlbeans.FlightType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis,
org.apache.xmlbeans.XmlOptions options)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (org.springframework.oxm.xmlbeans.FlightType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader()
.parse(xis, type, options);
}
/** @deprecated {@link XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream(xis, type, null);
}
/** @deprecated {@link XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis,
org.apache.xmlbeans.XmlOptions options)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream(xis, type, options);
}
private Factory() {
} // No instance of this class allowed
}
}

View File

@ -0,0 +1,243 @@
/*
* 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.
*/
/*
* An XML document type.
* Localname: flights
* Namespace: http://samples.springframework.org/flight
* Java type: org.springframework.samples.flight.FlightsDocument
*
* Automatically generated - do not modify.
*/
package org.springframework.oxm.xmlbeans;
/**
* A document containing one flights(@http://samples.springframework.org/flight) element.
*
* This is a complex type.
*/
public interface FlightsDocument extends org.apache.xmlbeans.XmlObject {
public static final org.apache.xmlbeans.SchemaType type =
(org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans
.typeSystemForClassLoader(FlightsDocument.class.getClassLoader(),
"schemaorg_apache_xmlbeans.system.s5EF858A5E57B2761C3670716FC0A909C")
.resolveHandle("flights4eb9doctype");
/** Gets the "flights" element */
org.springframework.oxm.xmlbeans.FlightsDocument.Flights getFlights();
/** Sets the "flights" element */
void setFlights(org.springframework.oxm.xmlbeans.FlightsDocument.Flights flights);
/** Appends and returns a new empty "flights" element */
org.springframework.oxm.xmlbeans.FlightsDocument.Flights addNewFlights();
/**
* An XML flights(@http://samples.springframework.org/flight).
*
* This is a complex type.
*/
public interface Flights extends org.apache.xmlbeans.XmlObject {
public static final org.apache.xmlbeans.SchemaType type =
(org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans
.typeSystemForClassLoader(Flights.class.getClassLoader(),
"schemaorg_apache_xmlbeans.system.s5EF858A5E57B2761C3670716FC0A909C")
.resolveHandle("flightseba8elemtype");
/** Gets a List of "flight" elements */
java.util.List<org.springframework.oxm.xmlbeans.FlightType> getFlightList();
/**
* Gets array of all "flight" elements
*
* @deprecated
*/
org.springframework.oxm.xmlbeans.FlightType[] getFlightArray();
/** Gets ith "flight" element */
org.springframework.oxm.xmlbeans.FlightType getFlightArray(int i);
/** Returns number of "flight" element */
int sizeOfFlightArray();
/** Sets array of all "flight" element */
void setFlightArray(org.springframework.oxm.xmlbeans.FlightType[] flightArray);
/** Sets ith "flight" element */
void setFlightArray(int i, org.springframework.oxm.xmlbeans.FlightType flight);
/** Inserts and returns a new empty value (as xml) as the ith "flight" element */
org.springframework.oxm.xmlbeans.FlightType insertNewFlight(int i);
/** Appends and returns a new empty value (as xml) as the last "flight" element */
org.springframework.oxm.xmlbeans.FlightType addNewFlight();
/** Removes the ith "flight" element */
void removeFlight(int i);
/** A factory class with static methods for creating instances of this type. */
public static final class Factory {
public static org.springframework.oxm.xmlbeans.FlightsDocument.Flights newInstance() {
return (org.springframework.oxm.xmlbeans.FlightsDocument.Flights) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().newInstance(type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument.Flights newInstance(org.apache.xmlbeans.XmlOptions options) {
return (org.springframework.oxm.xmlbeans.FlightsDocument.Flights) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().newInstance(type, options);
}
private Factory() {
} // No instance of this class allowed
}
}
/** A factory class with static methods for creating instances of this type. */
public static final class Factory {
public static org.springframework.oxm.xmlbeans.FlightsDocument newInstance() {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().newInstance(type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument newInstance(org.apache.xmlbeans.XmlOptions options) {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().newInstance(type, options);
}
/** @param xmlAsString the string value to parse */
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.lang.String xmlAsString)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(xmlAsString, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.lang.String xmlAsString,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(xmlAsString, type, options);
}
/** @param file the file from which to load an xml document */
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.io.File file)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(file, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.io.File file,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(file, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.net.URL u)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(u, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.net.URL u,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(u, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.io.InputStream is)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(is, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.io.InputStream is,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(is, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.io.Reader r)
throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(r, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(java.io.Reader r,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(r, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(javax.xml.stream.XMLStreamReader sr)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(sr, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(javax.xml.stream.XMLStreamReader sr,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(sr, type, options);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(org.w3c.dom.Node node)
throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(node, type, null);
}
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(org.w3c.dom.Node node,
org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(node, type, options);
}
/** @deprecated {@link XMLInputStream} */
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(xis, type, null);
}
/** @deprecated {@link XMLInputStream} */
public static org.springframework.oxm.xmlbeans.FlightsDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis,
org.apache.xmlbeans.XmlOptions options)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (org.springframework.oxm.xmlbeans.FlightsDocument) org.apache.xmlbeans.XmlBeans
.getContextTypeLoader().parse(xis, type, options);
}
/** @deprecated {@link XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream(xis, type, null);
}
/** @deprecated {@link XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis,
org.apache.xmlbeans.XmlOptions options)
throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream(xis, type, options);
}
private Factory() {
} // No instance of this class allowed
}
}

View File

@ -19,12 +19,15 @@ import java.io.ByteArrayOutputStream;
import javax.xml.transform.stream.StreamResult;
import org.apache.xmlbeans.XmlObject;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.oxm.AbstractMarshallerTestCase;
import org.springframework.oxm.Marshaller;
import org.springframework.samples.flight.FlightType;
import org.springframework.samples.flight.FlightsDocument;
import org.springframework.samples.flight.FlightsDocument.Flights;
@Ignore
public class XmlBeansMarshallerTest extends AbstractMarshallerTestCase {
@Override
@ -32,30 +35,26 @@ public class XmlBeansMarshallerTest extends AbstractMarshallerTestCase {
return new XmlBeansMarshaller();
}
public void testMarshalNonXmlObject() throws Exception {
try {
marshaller.marshal(new Object(), new StreamResult(new ByteArrayOutputStream()));
fail("XmlBeansMarshaller did not throw ClassCastException for non-XmlObject");
}
catch (ClassCastException e) {
// Expected behavior
}
}
@Override
protected Object createFlights() {
FlightsDocument flightsDocument = FlightsDocument.Factory.newInstance();
Flights flights = flightsDocument.addNewFlights();
FlightsDocument.Flights flights = flightsDocument.addNewFlights();
FlightType flightType = flights.addNewFlight();
flightType.setNumber(42L);
return flightsDocument;
}
public void testSupports() throws Exception {
@Test(expected = ClassCastException.class)
public void testMarshalNonXmlObject() throws Exception {
marshaller.marshal(new Object(), new StreamResult(new ByteArrayOutputStream()));
}
@Test
public void supports() throws Exception {
assertTrue("XmlBeansMarshaller does not support XmlObject", marshaller.supports(XmlObject.class));
assertFalse("XmlBeansMarshaller supports other objects", marshaller.supports(Object.class));
assertTrue("XmlBeansMarshaller does not support FlightsDocument", marshaller.supports(FlightsDocument.class));
assertTrue("XmlBeansMarshaller does not support Flights", marshaller.supports(Flights.class));
assertTrue("XmlBeansMarshaller does not support Flights", marshaller.supports(FlightsDocument.Flights.class));
assertTrue("XmlBeansMarshaller does not support FlightType", marshaller.supports(FlightType.class));
}
}

View File

@ -19,16 +19,19 @@ import java.io.StringReader;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.oxm.AbstractUnmarshallerTestCase;
import org.springframework.oxm.Unmarshaller;
import org.springframework.samples.flight.FlightDocument;
import org.springframework.samples.flight.FlightType;
import org.springframework.samples.flight.FlightsDocument;
import org.springframework.samples.flight.FlightsDocument.Flights;
import org.springframework.xml.transform.StaxSource;
import org.springframework.xml.transform.StringSource;
import org.springframework.util.xml.StaxUtils;
@Ignore
public class XmlBeansUnmarshallerTest extends AbstractUnmarshallerTestCase {
@Override
@ -40,7 +43,7 @@ public class XmlBeansUnmarshallerTest extends AbstractUnmarshallerTestCase {
protected void testFlights(Object o) {
FlightsDocument flightsDocument = (FlightsDocument) o;
assertNotNull("FlightsDocument is null", flightsDocument);
Flights flights = flightsDocument.getFlights();
FlightsDocument.Flights flights = flightsDocument.getFlights();
assertEquals("Invalid amount of flight elements", 1, flights.sizeOfFlightArray());
testFlight(flights.getFlightArray(0));
}
@ -60,7 +63,7 @@ public class XmlBeansUnmarshallerTest extends AbstractUnmarshallerTestCase {
}
@Override
public void testUnmarshalPartialStaxSourceXmlStreamReader() throws Exception {
public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
streamReader.nextTag(); // skip to flights
@ -69,25 +72,17 @@ public class XmlBeansUnmarshallerTest extends AbstractUnmarshallerTestCase {
streamReader.nextTag(); // skip to flight
assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flight"),
streamReader.getName());
StaxSource source = new StaxSource(streamReader);
Source source = StaxUtils.createStaxSource(streamReader);
Object flight = unmarshaller.unmarshal(source);
testFlight(flight);
}
@Test(expected = XmlBeansValidationFailureException.class)
public void testValidate() throws Exception {
((XmlBeansMarshaller) unmarshaller).setValidating(true);
try {
String invalidInput = "<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" +
"<tns:flight><tns:number>abc</tns:number></tns:flight></tns:flights>";
unmarshaller.unmarshal(new StringSource(invalidInput));
fail("Expected a XmlBeansValidationFailureException");
}
catch (XmlBeansValidationFailureException ex) {
// expected
}
unmarshaller.unmarshal(new StreamSource(new StringReader(invalidInput)));
}
}

View File

@ -0,0 +1,61 @@
/*
* An XML document type.
* Localname: flight
* Namespace: http://samples.springframework.org/flight
* Java type: org.springframework.oxm.xmlbeans.FlightDocument
*
* Automatically generated - do not modify.
*/
package org.springframework.oxm.xmlbeans.impl;
/**
* A document containing one flight(@http://samples.springframework.org/flight) element.
*
* This is a complex type.
*/
public class FlightDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl
implements org.springframework.oxm.xmlbeans.FlightDocument {
public FlightDocumentImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
private static final javax.xml.namespace.QName FLIGHT$0 =
new javax.xml.namespace.QName("http://samples.springframework.org/flight", "flight");
/** Gets the "flight" element */
public org.springframework.oxm.xmlbeans.FlightType getFlight() {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightType target = null;
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().find_element_user(FLIGHT$0, 0);
if (target == null) {
return null;
}
return target;
}
}
/** Sets the "flight" element */
public void setFlight(org.springframework.oxm.xmlbeans.FlightType flight) {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightType target = null;
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().find_element_user(FLIGHT$0, 0);
if (target == null) {
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().add_element_user(FLIGHT$0);
}
target.set(flight);
}
}
/** Appends and returns a new empty "flight" element */
public org.springframework.oxm.xmlbeans.FlightType addNewFlight() {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightType target = null;
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().add_element_user(FLIGHT$0);
return target;
}
}
}

View File

@ -0,0 +1,73 @@
/*
* XML Type: flightType
* Namespace: http://samples.springframework.org/flight
* Java type: org.springframework.samples.flight.FlightType
*
* Automatically generated - do not modify.
*/
package org.springframework.oxm.xmlbeans.impl;
/**
* An XML flightType(@http://samples.springframework.org/flight).
*
* This is a complex type.
*/
public class FlightTypeImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl
implements org.springframework.oxm.xmlbeans.FlightType {
public FlightTypeImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
private static final javax.xml.namespace.QName NUMBER$0 =
new javax.xml.namespace.QName("http://samples.springframework.org/flight", "number");
/** Gets the "number" element */
public long getNumber() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue) get_store().find_element_user(NUMBER$0, 0);
if (target == null) {
return 0L;
}
return target.getLongValue();
}
}
/** Gets (as xml) the "number" element */
public org.apache.xmlbeans.XmlLong xgetNumber() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.XmlLong target = null;
target = (org.apache.xmlbeans.XmlLong) get_store().find_element_user(NUMBER$0, 0);
return target;
}
}
/** Sets the "number" element */
public void setNumber(long number) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue) get_store().find_element_user(NUMBER$0, 0);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue) get_store().add_element_user(NUMBER$0);
}
target.setLongValue(number);
}
}
/** Sets (as xml) the "number" element */
public void xsetNumber(org.apache.xmlbeans.XmlLong number) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.XmlLong target = null;
target = (org.apache.xmlbeans.XmlLong) get_store().find_element_user(NUMBER$0, 0);
if (target == null) {
target = (org.apache.xmlbeans.XmlLong) get_store().add_element_user(NUMBER$0);
}
target.set(number);
}
}
}

View File

@ -0,0 +1,200 @@
/*
* An XML document type.
* Localname: flights
* Namespace: http://samples.springframework.org/flight
* Java type: org.springframework.samples.flight.FlightsDocument
*
* Automatically generated - do not modify.
*/
package org.springframework.oxm.xmlbeans.impl;
/**
* A document containing one flights(@http://samples.springframework.org/flight) element.
*
* This is a complex type.
*/
public class FlightsDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl
implements org.springframework.oxm.xmlbeans.FlightsDocument {
public FlightsDocumentImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
private static final javax.xml.namespace.QName FLIGHTS$0 =
new javax.xml.namespace.QName("http://samples.springframework.org/flight", "flights");
/** Gets the "flights" element */
public org.springframework.oxm.xmlbeans.FlightsDocument.Flights getFlights() {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightsDocument.Flights target = null;
target = (org.springframework.oxm.xmlbeans.FlightsDocument.Flights) get_store()
.find_element_user(FLIGHTS$0, 0);
if (target == null) {
return null;
}
return target;
}
}
/** Sets the "flights" element */
public void setFlights(org.springframework.oxm.xmlbeans.FlightsDocument.Flights flights) {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightsDocument.Flights target = null;
target = (org.springframework.oxm.xmlbeans.FlightsDocument.Flights) get_store()
.find_element_user(FLIGHTS$0, 0);
if (target == null) {
target = (org.springframework.oxm.xmlbeans.FlightsDocument.Flights) get_store()
.add_element_user(FLIGHTS$0);
}
target.set(flights);
}
}
/** Appends and returns a new empty "flights" element */
public org.springframework.oxm.xmlbeans.FlightsDocument.Flights addNewFlights() {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightsDocument.Flights target = null;
target = (org.springframework.oxm.xmlbeans.FlightsDocument.Flights) get_store().add_element_user(FLIGHTS$0);
return target;
}
}
/**
* An XML flights(@http://samples.springframework.org/flight).
*
* This is a complex type.
*/
public static class FlightsImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl
implements org.springframework.oxm.xmlbeans.FlightsDocument.Flights {
public FlightsImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
private static final javax.xml.namespace.QName FLIGHT$0 =
new javax.xml.namespace.QName("http://samples.springframework.org/flight", "flight");
/** Gets a List of "flight" elements */
public java.util.List<org.springframework.oxm.xmlbeans.FlightType> getFlightList() {
final class FlightList extends java.util.AbstractList<org.springframework.oxm.xmlbeans.FlightType> {
public org.springframework.oxm.xmlbeans.FlightType get(int i) {
return FlightsImpl.this.getFlightArray(i);
}
public org.springframework.oxm.xmlbeans.FlightType set(int i,
org.springframework.oxm.xmlbeans.FlightType o) {
org.springframework.oxm.xmlbeans.FlightType old = FlightsImpl.this.getFlightArray(i);
FlightsImpl.this.setFlightArray(i, o);
return old;
}
public void add(int i, org.springframework.oxm.xmlbeans.FlightType o) {
FlightsImpl.this.insertNewFlight(i).set(o);
}
public org.springframework.oxm.xmlbeans.FlightType remove(int i) {
org.springframework.oxm.xmlbeans.FlightType old = FlightsImpl.this.getFlightArray(i);
FlightsImpl.this.removeFlight(i);
return old;
}
public int size() {
return FlightsImpl.this.sizeOfFlightArray();
}
}
synchronized (monitor()) {
check_orphaned();
return new FlightList();
}
}
/** Gets array of all "flight" elements */
public org.springframework.oxm.xmlbeans.FlightType[] getFlightArray() {
synchronized (monitor()) {
check_orphaned();
java.util.List targetList = new java.util.ArrayList();
get_store().find_all_element_users(FLIGHT$0, targetList);
org.springframework.oxm.xmlbeans.FlightType[] result =
new org.springframework.oxm.xmlbeans.FlightType[targetList.size()];
targetList.toArray(result);
return result;
}
}
/** Gets ith "flight" element */
public org.springframework.oxm.xmlbeans.FlightType getFlightArray(int i) {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightType target = null;
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().find_element_user(FLIGHT$0, i);
if (target == null) {
throw new IndexOutOfBoundsException();
}
return target;
}
}
/** Returns number of "flight" element */
public int sizeOfFlightArray() {
synchronized (monitor()) {
check_orphaned();
return get_store().count_elements(FLIGHT$0);
}
}
/** Sets array of all "flight" element */
public void setFlightArray(org.springframework.oxm.xmlbeans.FlightType[] flightArray) {
synchronized (monitor()) {
check_orphaned();
arraySetterHelper(flightArray, FLIGHT$0);
}
}
/** Sets ith "flight" element */
public void setFlightArray(int i, org.springframework.oxm.xmlbeans.FlightType flight) {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightType target = null;
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().find_element_user(FLIGHT$0, i);
if (target == null) {
throw new IndexOutOfBoundsException();
}
target.set(flight);
}
}
/** Inserts and returns a new empty value (as xml) as the ith "flight" element */
public org.springframework.oxm.xmlbeans.FlightType insertNewFlight(int i) {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightType target = null;
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().insert_element_user(FLIGHT$0, i);
return target;
}
}
/** Appends and returns a new empty value (as xml) as the last "flight" element */
public org.springframework.oxm.xmlbeans.FlightType addNewFlight() {
synchronized (monitor()) {
check_orphaned();
org.springframework.oxm.xmlbeans.FlightType target = null;
target = (org.springframework.oxm.xmlbeans.FlightType) get_store().add_element_user(FLIGHT$0);
return target;
}
}
/** Removes the ith "flight" element */
public void removeFlight(int i) {
synchronized (monitor()) {
check_orphaned();
get_store().remove_element(FLIGHT$0, i);
}
}
}
}

View File

@ -0,0 +1,34 @@
/*
* 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.xstream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("flight")
public class AnnotatedFlight {
@XStreamAlias("number")
private long flightNumber;
public long getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(long number) {
this.flightNumber = number;
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 2007 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 java.io.StringWriter;
import javax.xml.transform.stream.StreamResult;
import org.custommonkey.xmlunit.XMLTestCase;
public class AnnotationXStreamMarshallerTest extends XMLTestCase {
private AnnotationXStreamMarshaller marshaller;
private static final String EXPECTED_STRING = "<flight><number>42</number></flight>";
private Flight flight;
protected void setUp() throws Exception {
marshaller = new AnnotationXStreamMarshaller();
marshaller.setAnnotatedClass(Flight.class);
flight = new Flight();
flight.setFlightNumber(42L);
}
public void testMarshalStreamResultWriter() throws Exception {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
marshaller.marshal(flight, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
}

View File

@ -17,7 +17,10 @@
package org.springframework.oxm.xstream;
import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
@ -27,42 +30,48 @@ import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import org.custommonkey.xmlunit.XMLTestCase;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.custommonkey.xmlunit.XMLAssert.assertXpathNotExists;
import org.easymock.MockControl;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.ContentHandler;
import org.springframework.xml.transform.StaxResult;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import org.springframework.util.xml.StaxUtils;
public class XStreamMarshallerTest extends XMLTestCase {
public class XStreamMarshallerTest {
private static final String EXPECTED_STRING = "<flight><flightNumber>42</flightNumber></flight>";
private XStreamMarshaller marshaller;
private Flight flight;
private AnnotatedFlight flight;
protected void setUp() throws Exception {
@Before
public void createMarshaller() throws Exception {
marshaller = new XStreamMarshaller();
Properties aliases = new Properties();
aliases.setProperty("flight", Flight.class.getName());
aliases.setProperty("flight", AnnotatedFlight.class.getName());
marshaller.setAliases(aliases);
flight = new Flight();
flight = new AnnotatedFlight();
flight.setFlightNumber(42L);
}
public void testMarshalDOMResult() throws Exception {
@Test
public void marshalDOMResult() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document = builder.newDocument();
@ -79,7 +88,8 @@ public class XStreamMarshallerTest extends XMLTestCase {
}
// see SWS-392
public void testMarshalDOMResultToExistentDocument() throws Exception {
@Test
public void marshalDOMResultToExistentDocument() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document existent = builder.newDocument();
@ -106,14 +116,16 @@ public class XStreamMarshallerTest extends XMLTestCase {
assertXMLEqual("Marshaller writes invalid DOMResult", expected, existent);
}
public void testMarshalStreamResultWriter() throws Exception {
@Test
public void marshalStreamResultWriter() throws Exception {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
marshaller.marshal(flight, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStreamResultOutputStream() throws Exception {
@Test
public void marshalStreamResultOutputStream() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult result = new StreamResult(os);
marshaller.marshal(flight, result);
@ -121,7 +133,8 @@ public class XStreamMarshallerTest extends XMLTestCase {
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, s);
}
public void testMarshalSaxResult() throws Exception {
@Test
public void marshalSaxResult() throws Exception {
MockControl handlerControl = MockControl.createStrictControl(ContentHandler.class);
handlerControl.setDefaultMatcher(MockControl.ALWAYS_MATCHER);
ContentHandler handlerMock = (ContentHandler) handlerControl.getMock();
@ -139,84 +152,106 @@ public class XStreamMarshallerTest extends XMLTestCase {
handlerControl.verify();
}
public void testMarshalStaxResultXMLStreamWriter() throws Exception {
@Test
public void marshalStaxResultXMLStreamWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
StaxResult result = new StaxResult(streamWriter);
Result result = StaxUtils.createStaxResult(streamWriter);
marshaller.marshal(flight, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testMarshalStaxResultXMLEventWriter() throws Exception {
@Test
public void marshalStaxResultXMLEventWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
StaxResult result = new StaxResult(eventWriter);
Result result = StaxUtils.createStaxResult(eventWriter);
marshaller.marshal(flight, result);
assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
public void testConverters() throws Exception {
@Test
public void converters() throws Exception {
marshaller.setConverters(new Converter[]{new EncodedByteArrayConverter()});
byte[] buf = new byte[]{0x1, 0x2};
StringResult result = new StringResult();
marshaller.marshal(buf, result);
assertXMLEqual("<byte-array>AQI=</byte-array>", result.toString());
StringSource source = new StringSource(result.toString());
byte[] bufResult = (byte[]) marshaller.unmarshal(source);
Writer writer = new StringWriter();
marshaller.marshal(buf, new StreamResult(writer));
assertXMLEqual("<byte-array>AQI=</byte-array>", writer.toString());
Reader reader = new StringReader(writer.toString());
byte[] bufResult = (byte[]) marshaller.unmarshal(new StreamSource(reader));
assertTrue("Invalid result", Arrays.equals(buf, bufResult));
}
public void testUseAttributesFor() throws Exception {
@Test
public void useAttributesFor() throws Exception {
marshaller.setUseAttributeForTypes(new Class[]{Long.TYPE});
StringResult result = new StringResult();
marshaller.marshal(flight, result);
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight flightNumber=\"42\" />";
assertXMLEqual("Marshaller does not use attributes", expected, result.toString());
assertXMLEqual("Marshaller does not use attributes", expected, writer.toString());
}
public void testUseAttributesForStringClassMap() throws Exception {
@Test
public void useAttributesForStringClassMap() throws Exception {
marshaller.setUseAttributeFor(Collections.singletonMap("flightNumber", Long.TYPE));
StringResult result = new StringResult();
marshaller.marshal(flight, result);
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight flightNumber=\"42\" />";
assertXMLEqual("Marshaller does not use attributes", expected, result.toString());
assertXMLEqual("Marshaller does not use attributes", expected, writer.toString());
}
public void testUseAttributesForClassStringMap() throws Exception {
marshaller.setUseAttributeFor(Collections.singletonMap(Flight.class, "flightNumber"));
StringResult result = new StringResult();
marshaller.marshal(flight, result);
@Test
public void useAttributesForClassStringMap() throws Exception {
marshaller.setUseAttributeFor(Collections.singletonMap(AnnotatedFlight.class, "flightNumber"));
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight flightNumber=\"42\" />";
assertXMLEqual("Marshaller does not use attributes", expected, result.toString());
assertXMLEqual("Marshaller does not use attributes", expected, writer.toString());
}
public void testOmitField() throws Exception {
marshaller.addOmittedField(Flight.class, "flightNumber");
StringResult result = new StringResult();
marshaller.marshal(flight, result);
assertXpathNotExists("/flight/flightNumber", result.toString());
@Test
public void omitField() throws Exception {
marshaller.addOmittedField(AnnotatedFlight.class, "flightNumber");
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertXpathNotExists("/flight/flightNumber", writer.toString());
}
public void testOmitFields() throws Exception {
Map omittedFieldsMap = Collections.singletonMap(Flight.class, "flightNumber");
@Test
public void omitFields() throws Exception {
Map omittedFieldsMap = Collections.singletonMap(AnnotatedFlight.class, "flightNumber");
marshaller.setOmittedFields(omittedFieldsMap);
StringResult result = new StringResult();
marshaller.marshal(flight, result);
assertXpathNotExists("/flight/flightNumber", result.toString());
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertXpathNotExists("/flight/flightNumber", writer.toString());
}
public void testDriver() throws Exception {
@Test
public void driver() throws Exception {
marshaller.setStreamDriver(new JettisonMappedXmlDriver());
StringResult result = new StringResult();
marshaller.marshal(flight, result);
assertEquals("Invalid result", "{\"flight\":{\"flightNumber\":\"42\"}}", result.toString());
Object o = marshaller.unmarshal(new StringSource(result.toString()));
assertTrue("Unmarshalled object is not Flights", o instanceof Flight);
Flight unflight = (Flight) o;
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertEquals("Invalid result", "{\"flight\":{\"flightNumber\":42}}", writer.toString());
Object o = marshaller.unmarshal(new StreamSource(new StringReader(writer.toString())));
assertTrue("Unmarshalled object is not Flights", o instanceof AnnotatedFlight);
AnnotatedFlight unflight = (AnnotatedFlight) o;
assertNotNull("Flight is null", unflight);
assertEquals("Number is invalid", 42L, unflight.getFlightNumber());
}
@Test
public void testMarshalStreamResultWriter() throws Exception {
marshaller.setAnnotatedClass(AnnotatedFlight.class);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
AnnotatedFlight flight = new AnnotatedFlight();
flight.setFlightNumber(42);
marshaller.marshal(flight, result);
String expected = "<flight><number>42</number></flight>";
assertXMLEqual("Marshaller writes invalid StreamResult", expected, writer.toString());
}
}

View File

@ -19,41 +19,45 @@ package org.springframework.oxm.xstream;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import junit.framework.TestCase;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.springframework.xml.transform.StaxSource;
import org.springframework.util.xml.StaxUtils;
public class XStreamUnmarshallerTest extends TestCase {
public class XStreamUnmarshallerTest {
protected static final String INPUT_STRING = "<flight><flightNumber>42</flightNumber></flight>";
private XStreamMarshaller unmarshaller;
protected void setUp() throws Exception {
@Before
public void creteUnmarshaller() throws Exception {
unmarshaller = new XStreamMarshaller();
Properties aliases = new Properties();
aliases.setProperty("flight", Flight.class.getName());
aliases.setProperty("flight", AnnotatedFlight.class.getName());
unmarshaller.setAliases(aliases);
}
private void testFlight(Object o) {
assertTrue("Unmarshalled object is not Flights", o instanceof Flight);
Flight flight = (Flight) o;
assertTrue("Unmarshalled object is not Flights", o instanceof AnnotatedFlight);
AnnotatedFlight flight = (AnnotatedFlight) o;
assertNotNull("Flight is null", flight);
assertEquals("Number is invalid", 42L, flight.getFlightNumber());
}
public void testUnmarshalDomSource() throws Exception {
@Test
public void unmarshalDomSource() throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(INPUT_STRING)));
DOMSource source = new DOMSource(document);
@ -61,21 +65,24 @@ public class XStreamUnmarshallerTest extends TestCase {
testFlight(flight);
}
public void testUnmarshalStaxSourceXmlStreamReader() throws Exception {
@Test
public void unmarshalStaxSourceXmlStreamReader() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
StaxSource source = new StaxSource(streamReader);
Source source = StaxUtils.createStaxSource(streamReader);
Object flights = unmarshaller.unmarshal(source);
testFlight(flights);
}
public void testUnmarshalStreamSourceInputStream() throws Exception {
@Test
public void unmarshalStreamSourceInputStream() throws Exception {
StreamSource source = new StreamSource(new ByteArrayInputStream(INPUT_STRING.getBytes("UTF-8")));
Object flights = unmarshaller.unmarshal(source);
testFlight(flights);
}
public void testUnmarshalStreamSourceReader() throws Exception {
@Test
public void unmarshalStreamSourceReader() throws Exception {
StreamSource source = new StreamSource(new StringReader(INPUT_STRING));
Object flights = unmarshaller.unmarshal(source);
testFlight(flights);

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">
<oxm:jaxb2-marshaller id="contextPathMarshaller" contextPath="org.springframework.oxm.jaxb2"/>
<oxm:jaxb2-marshaller id="classesMarshaller">
<oxm:class-to-be-bound name="org.springframework.oxm.jaxb2.Flights"/>
<oxm:class-to-be-bound name="org.springframework.oxm.jaxb2.FlightType"/>
</oxm:jaxb2-marshaller>
</beans>

View File

@ -1,10 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">
<oxm:jaxb1-marshaller id="jaxb1Marshaller" contextPath="org.springframework.oxm.jaxb1"/>
<oxm:jibx-marshaller id="jibxMarshaller" target-class="org.springframework.oxm.jibx.Flights"/>
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<!--<oxm:jibx-marshaller id="jibxMarshaller" target-class="org.springframework.oxm.jibx.Flights"/>-->
<oxm:xmlbeans-marshaller id="xmlBeansMarshaller" options="xmlBeansOptions"/>
<bean id="xmlBeansOptions" class="org.springframework.oxm.xmlbeans.XmlOptionsFactoryBean">
@ -14,4 +13,11 @@
</props>
</property>
</bean>
<oxm:jaxb2-marshaller id="contextPathMarshaller" contextPath="org.springframework.oxm.jaxb"/>
<oxm:jaxb2-marshaller id="classesMarshaller">
<oxm:class-to-be-bound name="org.springframework.oxm.jaxb.Flights"/>
<oxm:class-to-be-bound name="org.springframework.oxm.jaxb.FlightType"/>
</oxm:jaxb2-marshaller>
</beans>

View File

@ -18,6 +18,7 @@
<conf name="itext" extends="runtime" description="JARs needed to create beans for iText"/>
<conf name="jasper-reports" extends="runtime" description="JARs needed to create beans for Jasper Reports"/>
<conf name="jexcelapi" extends="runtime" description="JARs needed to create beans for JExcelApi"/>
<conf name="oxm" extends="runtime" description="JARs needed to use the MarshallingMessageConverter"/>
<conf name="poi" extends="runtime" description="JARs needed to create beans for Poi"/>
<conf name="tiles" extends="runtime" description="JARs neeeded to create beans for Tiles"/>
<conf name="velocity" extends="runtime" description="JARs needed to create beans for Velocity"/>
@ -29,34 +30,57 @@
</publications>
<dependencies>
<dependency org="com.sun.syndication" name="com.springsource.com.sun.syndication" rev="0.9.0" conf="optional, feed->compile"/>
<dependency org="com.lowagie.text" name="com.springsource.com.lowagie.text" rev="2.0.8" conf="optional, itext->compile"/>
<dependency org="org.freemarker" name="com.springsource.freemarker" rev="2.3.12" conf="optional, freemarker->compile"/>
<dependency org="com.sun.syndication" name="com.springsource.com.sun.syndication" rev="0.9.0"
conf="optional, feed->compile"/>
<dependency org="com.lowagie.text" name="com.springsource.com.lowagie.text" rev="2.0.8"
conf="optional, itext->compile"/>
<dependency org="org.freemarker" name="com.springsource.freemarker" rev="2.3.12"
conf="optional, freemarker->compile"/>
<dependency org="javax.el" name="com.springsource.javax.el" rev="1.0.0" conf="provided->compile"/>
<dependency org="javax.servlet" name="com.springsource.javax.servlet" rev="2.5.0" conf="provided->compile"/>
<dependency org="javax.servlet" name="com.springsource.javax.servlet.jsp" rev="2.1.0" conf="provided->compile"/>
<dependency org="javax.servlet" name="com.springsource.javax.servlet.jsp.jstl" rev="1.1.2" conf="provided->compile"/>
<dependency org="net.sourceforge.jexcelapi" name="com.springsource.jxl" rev="2.6.6" conf="optional, jexcelapi->compile"/>
<dependency org="net.sourceforge.jasperreports" name="com.springsource.net.sf.jasperreports" rev="2.0.5" conf="optional, jasper-reports->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.fileupload" rev="1.2.0" conf="optional, commons-fileupload->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.logging" rev="1.1.1" conf="compile->compile"/>
<dependency org="org.apache.poi" name="com.springsource.org.apache.poi" rev="3.0.2.FINAL" conf="optional, poi->compile"/>
<dependency org="org.apache.tiles" name="com.springsource.org.apache.tiles" rev="2.0.5" conf="optional, tiles->compile"/>
<dependency org="org.apache.tiles" name="com.springsource.org.apache.tiles.core" rev="2.0.5.osgi" conf="optional, tiles->compile"/>
<dependency org="org.apache.tiles" name="com.springsource.org.apache.tiles.jsp" rev="2.0.5" conf="optional, tiles->compile"/>
<dependency org="org.apache.velocity" name="com.springsource.org.apache.velocity" rev="1.5.0" conf="optional, velocity->compile"/>
<dependency org="org.apache.velocity" name="com.springsource.org.apache.velocity.tools.view" rev="1.4.0" conf="optional, velocity->compile"/>
<dependency org="org.springframework" name="org.springframework.beans" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.context" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.context.support" rev="latest.integration" conf="optional, velocity, freemarker, jasper-reports->compile"/>
<dependency org="org.springframework" name="org.springframework.core" rev="latest.integration" conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.web" rev="latest.integration" conf="compile->compile"/>
<dependency org="javax.servlet" name="com.springsource.javax.servlet.jsp.jstl" rev="1.1.2"
conf="provided->compile"/>
<dependency org="net.sourceforge.jexcelapi" name="com.springsource.jxl" rev="2.6.6"
conf="optional, jexcelapi->compile"/>
<dependency org="net.sourceforge.jasperreports" name="com.springsource.net.sf.jasperreports" rev="2.0.5"
conf="optional, jasper-reports->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.fileupload" rev="1.2.0"
conf="optional, commons-fileupload->compile"/>
<dependency org="org.apache.commons" name="com.springsource.org.apache.commons.logging" rev="1.1.1"
conf="compile->compile"/>
<dependency org="org.apache.poi" name="com.springsource.org.apache.poi" rev="3.0.2.FINAL"
conf="optional, poi->compile"/>
<dependency org="org.apache.tiles" name="com.springsource.org.apache.tiles" rev="2.0.5"
conf="optional, tiles->compile"/>
<dependency org="org.apache.tiles" name="com.springsource.org.apache.tiles.core" rev="2.0.5.osgi"
conf="optional, tiles->compile"/>
<dependency org="org.apache.tiles" name="com.springsource.org.apache.tiles.jsp" rev="2.0.5"
conf="optional, tiles->compile"/>
<dependency org="org.apache.velocity" name="com.springsource.org.apache.velocity" rev="1.5.0"
conf="optional, velocity->compile"/>
<dependency org="org.apache.velocity" name="com.springsource.org.apache.velocity.tools.view" rev="1.4.0"
conf="optional, velocity->compile"/>
<dependency org="org.springframework" name="org.springframework.beans" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.context" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.context.support" rev="latest.integration"
conf="optional, velocity, freemarker, jasper-reports->compile"/>
<dependency org="org.springframework" name="org.springframework.core" rev="latest.integration"
conf="compile->compile"/>
<dependency org="org.springframework" name="org.springframework.oxm" rev="latest.integration"
conf="optional, oxm->compile"/>
<dependency org="org.springframework" name="org.springframework.web" rev="latest.integration"
conf="compile->compile"/>
<!-- test dependencies -->
<dependency org="org.junit" name="com.springsource.org.junit" rev="4.5.0" conf="test->runtime"/>
<dependency org="org.easymock" name="com.springsource.org.easymock" rev="2.3.0" conf="test->compile"/>
<dependency org="org.objectweb.asm" name="com.springsource.org.objectweb.asm" rev="2.2.3" conf="test->compile"/>
<dependency org="org.objectweb.asm" name="com.springsource.org.objectweb.asm.commons" rev="2.2.3" conf="test->compile"/>
<dependency org="org.custommonkey.xmlunit" name="com.springsource.org.custommonkey.xmlunit" rev="1.2.0" conf="test->compile"/>
<dependency org="org.objectweb.asm" name="com.springsource.org.objectweb.asm.commons" rev="2.2.3"
conf="test->compile"/>
<dependency org="org.custommonkey.xmlunit" name="com.springsource.org.custommonkey.xmlunit" rev="1.2.0"
conf="test->compile"/>
<dependency org="org.dom4j" name="com.springsource.org.dom4j" rev="1.6.1" conf="test->compile"/>
<dependency org="org.jaxen" name="com.springsource.org.jaxen" rev="1.1.1" conf="test->compile"/>
<dependency org="net.sourceforge.cglib" name="com.springsource.net.sf.cglib" rev="2.1.3" conf="test->compile"/>

View File

@ -0,0 +1,134 @@
/*
* Copyright 2007 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.web.servlet.view.xml;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamResult;
import org.springframework.beans.BeansException;
import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
/**
* Spring-MVC {@link View} that allows for response context to be rendered as the result of marshalling by a {@link
* Marshaller}.
*
* <p>The Object to be marshalled is supplied as a parameter in the model and then {@linkplain
* #locateToBeMarshalled(Map) detected} during response rendering. Users can either specify a specific entry in the
* model via the {@link #setModelKey(String) sourceKey} property or have Spring locate the Source object.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class MarshallingView extends AbstractUrlBasedView {
/** Default content type. Overridable as bean property. */
public static final String DEFAULT_CONTENT_TYPE = "application/xml";
private Marshaller marshaller;
private String modelKey;
/**
* Constructs a new <code>MarshallingView</code> with no {@link Marshaller} set. The marshaller must be set after
* construction by invoking {@link #setMarshaller(Marshaller)}.
*/
public MarshallingView() {
setContentType(DEFAULT_CONTENT_TYPE);
}
/** Constructs a new <code>MarshallingView</code> with the given {@link Marshaller} set. */
public MarshallingView(Marshaller marshaller) {
Assert.notNull(marshaller, "'marshaller' must not be null");
setContentType(DEFAULT_CONTENT_TYPE);
this.marshaller = marshaller;
}
/** Sets the {@link Marshaller} to be used by this view. */
public void setMarshaller(Marshaller marshaller) {
Assert.notNull(marshaller, "'marshaller' must not be null");
this.marshaller = marshaller;
}
/**
* Set the name of the model key that represents the object to be marshalled. If not specified, the model map will be
* searched for a supported value type.
*
* @see Marshaller#supports(Class)
*/
public void setModelKey(String modelKey) {
this.modelKey = modelKey;
}
@Override
protected void initApplicationContext() throws BeansException {
Assert.notNull(marshaller, "Property 'marshaller' is required");
}
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Object toBeMarshalled = locateToBeMarshalled(model);
if (toBeMarshalled == null) {
throw new ServletException("Unable to locate object to be marshalled in model: " + model);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
marshaller.marshal(toBeMarshalled, new StreamResult(bos));
response.setContentType(getContentType());
response.setContentLength(bos.size());
ServletOutputStream out = response.getOutputStream();
bos.writeTo(out);
out.flush();
}
/**
* Locates the object to be marshalled. The default implementation first attempts to look under the configured
* {@linkplain #setModelKey(String) model key}, if any, before attempting to locate an object of {@linkplain
* Marshaller#supports(Class) supported type}.
*
* @param model the model Map
* @return the Object to be marshalled (or <code>null</code> if none found)
* @throws ServletException if the model object specified by the {@linkplain #setModelKey(String) model key} is not
* supported by the marshaller
* @see #setModelKey(String)
*/
protected Object locateToBeMarshalled(Map model) throws ServletException {
if (this.modelKey != null) {
Object o = model.get(this.modelKey);
if (!this.marshaller.supports(o.getClass())) {
throw new ServletException("Model object [" + o + "] retrieved via key [" + modelKey +
"] is not supported by the Marshaller");
}
return o;
}
for (Object o : model.values()) {
if (this.marshaller.supports(o.getClass())) {
return o;
}
}
return null;
}
}

View File

@ -0,0 +1,7 @@
<html>
<body>
Support classes for providing a View implementation based on XML Marshalling.
</body>
</html>

View File

@ -0,0 +1,138 @@
/*
* Copyright 2007 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.web.servlet.view.xml;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamResult;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.oxm.Marshaller;
public class MarshallingViewTest {
private MarshallingView view;
private Marshaller marshallerMock;
@Before
public void createView() throws Exception {
marshallerMock = createMock(Marshaller.class);
view = new MarshallingView(marshallerMock);
}
@Test
public void testGetContentType() {
assertEquals("Invalid content type", "application/xml", view.getContentType());
}
@Test
public void renderModelKey() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
view.setModelKey(modelKey);
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
expect(marshallerMock.supports(Object.class)).andReturn(true);
marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class));
replay(marshallerMock);
view.render(model, request, response);
assertEquals("Invalid content type", "application/xml", response.getContentType());
assertEquals("Invalid content length", 0, response.getContentLength());
verify(marshallerMock);
}
@Test
public void renderModelKeyUnsupported() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
view.setModelKey(modelKey);
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
expect(marshallerMock.supports(Object.class)).andReturn(false);
replay(marshallerMock);
try {
view.render(model, request, response);
fail("ServletException expected");
}
catch (ServletException ex) {
// expected
}
verify(marshallerMock);
}
@Test
public void renderNoModelKey() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
expect(marshallerMock.supports(Object.class)).andReturn(true);
marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class));
replay(marshallerMock);
view.render(model, request, response);
assertEquals("Invalid content type", "application/xml", response.getContentType());
assertEquals("Invalid content length", 0, response.getContentLength());
verify(marshallerMock);
}
@Test
public void testRenderUnsupportedModel() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
expect(marshallerMock.supports(Object.class)).andReturn(false);
replay(marshallerMock);
try {
view.render(model, request, response);
fail("ServletException expected");
}
catch (ServletException ex) {
// expected
}
verify(marshallerMock);
}
}

View File

@ -268,10 +268,11 @@
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module" module-name="oxm" />
</component>
<component name="copyright">
<Base>
<setting name="state" value="2" />
<setting name="state" value="1" />
</Base>
</component>
</module>