Java and Spring development

Posts Tagged ‘JAXB

Spring WS client

with 5 comments

Introduction

The Spring WS client is a lightweight alternative that doesn’t need a WSDL to work. You code against a template like Spring’s other templates for communicating against a database or JMS server. This blog article demonstrates how to use Spring WS as a client with JAXB for the data binding and how to add pre and post processing behaviour with interceptors.

If you’re not familiar with generating JAXB classes, then take a look at this tutorial.

How to use the WebServiceTemplate class

Since Spring WS doesn’t use a service contract, you must know the request and response type. The test below demonstrates how to create and instantiate a request object of a JAXB generated class, call the marshallSendAndReceive method with it and how to cast the response object to an object of the JAXB generated response class. Finally, the test asserts that the service returned the expected result.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("test-config.xml")
public class AccountBalanceServiceTest {

	@Autowired
	private WebServiceTemplate webServiceTemplate;

	@Test
	public void testAccountBalanceService() {

		AccountBalanceRequest request = new ObjectFactory()
				.createAccountBalanceRequest();
		request.setName("Willy");
		request.setNumber("0987654321");
		AccountBalanceResponse response = (AccountBalanceResponse) webServiceTemplate
				.marshalSendAndReceive(request);

		assertEquals(BigDecimal.valueOf(100.5), response.getBalance());
	}
}

As you see, none web service specific information. All the web service details are hiding in the configuration.

Spring configuration

The test above requires a marshaller and WebServiceTemplate bean. The marshaller must specify the context path. That’s the package name for the generated JAXB classes.

<oxm:jaxb2-marshaller id="marshaller"
	contextPath="com.redpill.linpro.ws.account.balance.service" />

The template bean must specify the JAXB marshaller and the URI to the web service’s servlet URI.

<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">

	<property name="marshaller" ref="marshaller" />
	<property name="unmarshaller" ref="marshaller" />
	<property name="defaultUri"
		value="http://localhost:8081/ws-demo/account-balance-service" />
</bean>

Retrieving standard SOAP faults

When the SOAP response contains a SOAP fault, then Spring WS converts it into a SoapFaultClientException. This test calls a web service and expects an exception back:

@Test(expected = SoapFaultClientException.class)
public void testAccountBalanceServiceWithTooLongAccountNumber() {

	AccountBalanceRequest request = new AccountBalanceRequest();
	request.setName("Willy");
	request.setNumber("0987654321000000000000000000000000000");

	webServiceTemplate.marshalSendAndReceive(request);
}

It’s caught by the JUnit test in the same way as you can catch every Java exceptions.

Validating

The client part of Spring WS can validate the parsed XML before it sends the XML document. You only need to specify a validator interceptor in the configuration and reference to it from the WebServiceTemplate bean.

<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
	<property name="marshaller" ref="marshaller" />
	<property name="unmarshaller" ref="marshaller" />
	<property name="defaultUri"
		value="http://localhost:8081/ws-demo/account-balance-service" />
	<property name="interceptors">
		<list>
			<ref bean="payloadValidatingInterceptor" />
		</list>
	</property>
</bean>

<bean id="payloadValidatingInterceptor"
	class="org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor">
	<property name="schema"
		value="file:WebContent/WEB-INF/schemas/account-balance-service.xsd" />
	<property name="validateRequest" value="true" />
	<property name="validateResponse" value="true" />
</bean>

This configuration should have worked. But it doesn’t work on my machine with Spring WS 1.5.9.A. A snippet from the odd log message:

<XML validation error on request: cvc-complex-type.3.2.2: Attribute 'name' is not allowed to appear in element 'ns2:accountBalanceRequest'.>
<XML validation error on request: cvc-complex-type.4: Attribute 'name' must appear on element 'ns2:accountBalanceRequest'.>

You can click the link to see the whole log message.

ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - <XML validation error on request: cvc-complex-type.3.2.2: Attribute 'name' is not allowed to appear in element 'ns2:accountBalanceRequest'.>
ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - <XML validation error on request: cvc-complex-type.3.2.2: Attribute 'number' is not allowed to appear in element 'ns2:accountBalanceRequest'.>
ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - <XML validation error on request: cvc-complex-type.4: Attribute 'name' must appear on element 'ns2:accountBalanceRequest'.>
ERROR [org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor] - <XML validation error on request: cvc-complex-type.4: Attribute 'number' must appear on element 'ns2:accountBalanceRequest'.>

It’s an issue with the SAX validator and the DOM source element that represents the parsed XML. A quick fix to solve this problem is to transform the DOM source to a String. Create a StringReader with the String and create a StreamSource object with the StringReader. For all the details, see the source code:

public class PayloadValidatingInterceptorWithSourceFix extends
		PayloadValidatingInterceptor {

	@Override
	protected Source getValidationRequestSource(WebServiceMessage request) {
		return transformSourceToStreamSourceWithStringReader(request.getPayloadSource());
	}

	@Override
	protected Source getValidationResponseSource(WebServiceMessage response) {
		return transformSourceToStreamSourceWithStringReader(response.getPayloadSource());
	}

	Source transformSourceToStreamSourceWithStringReader(Source notValidatableSource) {
		final Source source;
		try {
			Transformer transformer = TransformerFactory.newInstance().newTransformer();

			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
					"yes");
			transformer.setOutputProperty(OutputKeys.INDENT, "no");
			StringWriter writer = new StringWriter();
			transformer.transform(notValidatableSource, new StreamResult(
					writer));

			String transformed = writer.toString();
			StringReader reader = new StringReader(transformed);
			source = new StreamSource(reader);

		} catch (TransformerException transformerException) {
			throw new WebServiceTransformerException(
					"Could not convert the source to a StreamSource with a StringReader",
					transformerException);
		}

		return source;
	}
}

And finally, replace the Spring interceptor bean with this bean:

<bean id="payloadValidatingInterceptorWithSourceFix"
	class="com.redpill.linpro.transport.account.ws.PayloadValidatingInterceptorWithSourceFix">
	<property name="schema"
		value="file:WebContent/WEB-INF/schemas/account-balance-service.xsd" />
	<property name="validateRequest" value="true" />
	<property name="validateResponse" value="true" />
</bean>

When the PayloadValidatingInterceptor work as expected, the interceptor will throw a WebServiceValidationException when you try to send a value that’s not valid according to the XSD schema.

Summary

It’s an elegant framework that’s easy to use.

The validation issues is a minus, but since it’s an open-source project, you always have the chance to replace or extend the classes you want.

The code used in this article was developed in my work time at Redpill Linpro. It can be downloaded here


Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.

Written by Espen

February 28, 2010 at 21:50

Generate JAXB classes from an XSD schema and the schema from an XML sample document

with 10 comments

Introduction

This tutorial demonstrates how to generate an XSD schema from a sample XML document and how to improve the schema before generating JABX classes from it.

The sample document used throughout this tutorial contains an order element as you can see here:

<order>
	<date>2010-01-01</date>
	<id>12345</id>
	<item name="Effective Java" type="BOOK" quantity="1" />
	<item name="Spring in Action" type="BOOK" quantity="1" />
	<item name="Gladiator" type="DVD" quantity="1" />
</order>

The motivation for creating a sample document first, is that it’s more simple and less verbose to write than an XSD schema. You can also generate an XSD schema from JAXB classes, but this tutorial generates JAXB classes from an XSD schema. This is because an XSD schema is language neutral and more feature rich for describing a data contract. For example the ability to add restrictions with regular expressions like this:

<xs:attribute name="number" use="required">
	simpleType>
		<xs:restriction base="xs:string">
			<xs:pattern value="\d{10}" />
		</xs:restriction>
	</xs:simpleType>
</xs:attribute>

Generate XSD schema from XML sample document with Trang

The Trang project lives here: http://code.google.com/p/jing-trang/

You can execute Trang’s Driver class with the XML sample document’s path and the path for the schema that will be generated to generate the schema. Another and probably more common way to generate is with Ant like this target:

<target name="generate-order-schema" description="Generates schema from XML with Trang">
	<mkdir dir="${xsd-folder}" />

	<java jar="${lib-generate-folder}/trang.jar" fork="true">
		<arg value="${xml-example-folder}/order.xml" />
		<arg value="${xsd-folder}/order-generated.xsd" />
	</java>

	<echo message="${xsd-folder}/order-generated.xsd was generated" />
</target>

After you have executed this target, remember to update the folder with the generated file if you’re using Eclipse.

Tweaking the generated XSD schema

I only specified the input file and the path to the generated file when I executed Trang. This results in a very simple XSD without namespace for example. See Trang’s manual for more advanced use. The generated schema looks like this:

<?xml version="1.0" encoding="UTF-8"?>
xmlns:xs="http://www.w3.org/2001/XMLSchema"
	elementFormDefault="qualified">
	<xs:element name="order">
		<xs:complexType>
			<xs:sequence>
				<xs:element ref="date" />
				<xs:element ref="id" />
				<xs:element maxOccurs="unbounded" ref="item" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>
	NMTOKEN" />
	<xs:element name="id" type="xs:integer" />
	<xs:element name="item">
		<xs:complexType>
			<xs:attribute name="name" use="required" />
			<xs:attribute name="quantity" use="required" type="xs:integer" />
			NCName" />
		</xs:complexType>
	</xs:element>
</xs:schema>

The generated schema is an excellent start, but you often want to add namespace, restrictions and often to change the type of some of the fields Trang guessed on. After some manual modifications, my schema looks like this:

<?xml version="1.0" encoding="UTF-8"?>
xmlns:xs="http://www.w3.org/2001/XMLSchema"
	elementFormDefault="qualified" targetNamespace="http://www.redpill-linpro.com/order"
	xmlns:o="http://www.redpill-linpro.com/order">

	<xs:element name="order">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="date" type="xs:date" />
				<xs:element name="id" type="xs:int" />
				<xs:element name="item" maxOccurs="unbounded">
					<xs:complexType>
						<xs:attribute name="name" use="required" type="xs:string" />
						<xs:attribute name="quantity" use="required" type="xs:int" />
						itemType" />
					</xs:complexType>
				</xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>

	<xs:simpleType name="itemType">
		<xs:restriction base="xs:string">
			<xs:enumeration value="BOOK" />
			<xs:enumeration value="DVD" />
			<xs:enumeration value="CD" />
		</xs:restriction>
	</xs:simpleType>
</xs:schema>

Another difference is that it’s only one xs:element in the tweaked version. This is because id or date doesn’t give any value alone, but only together as part of the order element.

A JAXB tips is to create an xs:element with a nested type element inside it. This enables JAXB to add an @XmlRoot annotation above the generated class. This annotation is necessary for JAXB to marshall your objects.

Working with XSD schema inside a good IDE

With an IDE like Eclipse, it’s quite easy to create an XML document from an XSD schema. The XML document below is created with Eclipse. The schema is relative to the document and is highlighted in the XML document. You should consider a URL instead of a relative path for other situations than simple testing.

<?xml version="1.0" encoding="UTF-8"?>
xmlns:o="http://www.redpill-linpro.com/order"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.redpill-linpro.com/order order.xsd ">
	<o:date>2001-01-01</o:date>
	<o:id>0</o:id>
	<o:item name="Effective Java" quantity="3" type="BOOK" />
	<o:item name="Spring in Action" quantity="1" type="BOOK" />
</o:order>

A good IDE that’s aware of the schema will also give you code completion and validation support. This screenshot shows code completion of enumeration values.

Testing the generated JAXB classes

The test below is a simple test that instantiates a JAXB generated order object. Then the object is marshalled to an XML document. The test asserts that the XML document contains some of the data from the order object. After this, it unmarshall the XML document back to an Order object again. Finally, the two order objects are compared against each other.

public class OrderJaxbTest {

	@Test
	public void testOrder() throws Exception {
		Order order = createJaxbOrder();

		String xmlDocument = marshallOrderToXml(order);
		assertTrue(xmlDocument.contains("type=\"CD\" quantity=\"2\" name=\"Effective Java\""));

		Order unmarshalledOrder = unmarshallToOrderFromXml(xmlDocument);
		assertEquals(order.getId(), unmarshalledOrder.getId());
	}

	private Order unmarshallToOrderFromXml(String xmlDocument)
			throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(Order.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		StringReader reader = new StringReader(xmlDocument);
		Order unmarshalledOrder = (Order) unmarshaller.unmarshal(reader);
		return unmarshalledOrder;
	}

	private Order createJaxbOrder() throws DatatypeConfigurationException {
		Order order = new ObjectFactory().createOrder();
		order.setDate(DatatypeFactory.newInstance()
				.newXMLGregorianCalendar(2010, 5, 5, 12, 0, 0, 0, 1));
		order.setId(1);

		Item item = new Item();
		item.setName("Effective Java");
		item.setQuantity(2);
		item.setType(ItemType.CD);
		order.getItem().add(item);

		return order;
	}

	public String marshallOrderToXml(Order order) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(Order.class);
		Marshaller marshaller =context.createMarshaller();
		StringWriter writer = new StringWriter();
		marshaller.marshal(order, writer);

		return writer.toString();
	}
}

For simplicity, I send an StringWriter to the JAXB marshaller and an StringReader to the JAXB unmarshaller. It’s just to replace the reader and writer if you want to work against the file system.

Summary

To generate a basic version of the schema and then incrementally improve that schema works really well. It exists several frameworks and tools that can generate the schema. I have only evaluated Trang, but it does the job well and it’s an open source project that’s very easy to use. Also, to generate the JAXB classes from an XSD schema ensures that you’re 100% language neutral. JAXB is just one of many frameworks that can parse XML. It’s the Java standard parsing framework and some of its benefits are that it provides type safety and abstracts away the XML parsing behind a Java API.

To generate JAXB classes from an XSD schema is also an excellent start for writing contract-first web services with frameworks like Spring WS and CXF. These frameworks can be configured to use JAXB for the parsing. I will write more about Spring WS in a later article.

The code used in this article was developed in my work time at Redpill Linpro. It can be downloaded from here.


Redpill Linpro is the leading provider of Professional Open Source services and products in the Nordic region.

Written by Espen

February 26, 2010 at 12:36

Posted in Web Services

Tagged with , , ,