Turn contracts into documentation

In part one I’ve shown how to turn contracts into code. In this part I am going to show how to turn contracts into documentation.

Using the contract as a model for both code generation and documentation can save a lot of time. That is because the contract represents a single source of truth, which can be used by developers and business people alike. Just like you would probably do when you design BPMN models together with people from business you can design service contracts in the same way. Designing service contracts together with business people fosters the notion of services as business assets rather than just technical artefacts. Beside the time savings this creates mutual understanding amongst developers and business people. It facilitates collaboration and aligns business and IT. It work especially well in agile contexts in which business and IT work closely together.

But in order to be able to generate proper documentation from XML schema it is necessary to document the schema very thoroughly. Luckily there is a standardized way to do that using <xs:annotation> and <xs:documentation>. The following listing shows how to do it right.


<xs:element name="PerformSimpleCalculationRequest">
  <xs:annotation><xs:documentation>Performs a simple calculation</xs:documentation></xs:annotation>
  <xs:complexType>
    <xs:sequence>
      <xs:element name="operation" type="tns:Operation" minOccurs="1" maxOccurs="1">
        <xs:annotation>
          <xs:documentation xml:lang="EN">Operation to perform</xs:documentation>
          <xs:documentation xml:lang="DE">Operation zur Ausführung</xs:documentation>
        </xs:annotation>
      </xs:element>
      ...
    </xs:sequence>
  </xs:complexType>
</xs:element>

You can see the full listing in the previous blog post.
It is best practice to document every aspect in the schema in a way that can be understood by humans. Ideally not only by technicans but by business people as well. To achive that it is essential to use the right language from the respective business domain. As shown in the listing it is even possible to add documentation in multiple languages.

As XML schema itself is XML we can easily validate and transform it to HTML using XSD and XSLT. A template can be found as part of the example project.

The stylesheet can be linked to the XSD using the directive <?xml-stylesheet type=”text/xsl” href=”contract.xsl”?> within the XSD. If you open the XSD in a web browser it will be transformed right away and show the HTML output.

Alternatively you can transform the XSD on the commandline using msxsl.exe. Just type the following to generate the HTML documentation.

msxsl calculator.xsd contract.xsl -o calculator.html

Another option is to automate the transformation process using the Maven plugin org.codehaus.mojo:xml-maven-plugin as you can see in the following excerpt from the POM file.

<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>xml-maven-plugin</artifactId>
	<version>1.0</version>
  <inherited>false</inherited>
  <executions>
		<execution>
			<id>transform</id>
			<goals>
				<goal>transform</goal>
			</goals>
			<phase>install</phase>
		</execution>
	</executions>
	<configuration>
		<transformationSets>
			<transformationSet>
				<dir>api/src/main/resources/xsd</dir>
				<stylesheet>${project.basedir}/repo/transform/xsl/contract.xsl</stylesheet>
				<outputDir>target/repository</outputDir>
				<fileMappers>
					<fileMapper implementation="org.codehaus.plexus.components.io.filemappers.RegExpFileMapper">
						<pattern>^(.*)\.xsd$</pattern>
						<replacement>contract.html</replacement>
					</fileMapper>
				</fileMappers>
			</transformationSet>
		</transformationSets>
	</configuration>
</plugin>

The result is a HTML contract documentation in the target/repository directory. This documentation can for instance be uploaded to a Wiki which serves as a service repository. It is lightweight, easy to use and highly recommended as it greatly helps to increase the likelyness of service reuse.

It is definitely recommended to develop service contracts in workshops with people from IT and business. The person who moderates such a workshop can be called a BizDev, as he/she needs understanding of the business domain and technology alike. Doing that can greatly reduce misconceptions and create awareness of services as reusable business assets. Give it a try!

Turn contracts into code

Interfaces are one of the most important parts in software design. Designing software around properly defined interfaces has many benefits for instance in the areas of consistency, maintainability and reuse. A well written contract describes precisely how software artefacts (or services) interact with each other. Approaches such as Sustainable Service Design or the BiPRO standards rely on contracts based on XML Schema (xsd). As they start with the contract design, they are called contract or schema first approaches.
Once you have a contract the question is how to turn it into code. In the Java world JAXB is the first choice. Lets’s see how we can generate Java sourcecode from the schema.

We start with a simple schema shown in the following listing.

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="contract.xsl"?>
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xml="http://www.w3.org/XML/1998/namespace"    
    xmlns:service="http://www.pleus.net/services"
    xmlns:tns="http://www.pleus.net/services/calculator/api/model"
	targetNamespace="http://www.pleus.net/services/calculator/api/model"
	elementFormDefault="qualified" attributeFormDefault="qualified"
	version="1.0">
	  
    <!-- ################################################### -->
	<!-- ################### Messages ###################### -->
    <!-- ################################################### -->

    
	<xs:element name="PerformSimpleCalculationRequest">
		<xs:annotation><xs:documentation>Performs a simple calculation</xs:documentation></xs:annotation>
		<xs:complexType>
			<xs:sequence>
				<xs:element name="operation" type="tns:Operation" minOccurs="1" maxOccurs="1">
					<xs:annotation>
                        <xs:documentation xml:lang="EN">Operation to perform</xs:documentation>
                        <xs:documentation xml:lang="DE">Operation zur Ausführung</xs:documentation>
                    </xs:annotation>
				</xs:element>
				<xs:element name="value-a" type="tns:decimal9F2" minOccurs="1" maxOccurs="1">
					<xs:annotation><xs:documentation>First value</xs:documentation></xs:annotation>
				</xs:element>
				<xs:element name="value-b" type="xs:decimal" minOccurs="1" maxOccurs="1">
					<xs:annotation><xs:documentation>Second value</xs:documentation></xs:annotation>
				</xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
    
	<xs:element name="PerformSimpleCalculationResponse">
		<xs:annotation><xs:documentation>Result of a simple calculation</xs:documentation></xs:annotation>
		<xs:complexType>
			<xs:sequence>
				<xs:element name="result" type="xs:decimal" minOccurs="1" maxOccurs="1">
					<xs:annotation><xs:documentation>Result</xs:documentation></xs:annotation>
				</xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
    

   <xs:element name="CalculatorError">
   	  <xs:annotation><xs:documentation>Provides error information</xs:documentation></xs:annotation>
      <xs:complexType>
         <xs:sequence>
				<xs:element name="message" type="xs:string" minOccurs="1" maxOccurs="1">
					<xs:annotation><xs:documentation>Fehlermeldung</xs:documentation></xs:annotation>
				</xs:element>
				<xs:element name="code" type="xs:int" minOccurs="1" maxOccurs="1">
					<xs:annotation><xs:documentation>Fehlercode</xs:documentation></xs:annotation>
				</xs:element>
         </xs:sequence>
      </xs:complexType>
   </xs:element>
	
    <!-- ################################################### -->
    <!-- ################# Type definitions ################ -->
    <!-- ################################################### -->

	<!--  Enum type  -->
	 <xs:simpleType name="Operation">
	    <xs:annotation><xs:documentation>Defines the arithmetic operations</xs:documentation></xs:annotation>
		<xs:restriction base="xs:string">
			<xs:enumeration value="ADD"><xs:annotation><xs:documentation>Add</xs:documentation></xs:annotation></xs:enumeration>
			<xs:enumeration value="SUBTRACT"><xs:annotation><xs:documentation>Substract</xs:documentation></xs:annotation></xs:enumeration>
			<xs:enumeration value="MULTIPLY"><xs:annotation><xs:documentation>Multiply</xs:documentation></xs:annotation></xs:enumeration>
			<xs:enumeration value="DIVIDE"><xs:annotation><xs:documentation>Divide</xs:documentation></xs:annotation></xs:enumeration>
		</xs:restriction>
	</xs:simpleType>

        <xs:simpleType name="decimal9F2">
          <xs:restriction base="xs:decimal">
            <xs:totalDigits value="9"/>
            <xs:fractionDigits value="2"/>
          </xs:restriction>
        </xs:simpleType>

</xs:schema>

The schema is part of an example project which can be downloaded here.

A more appealing representation would look as follows:

In order to turn this schema into code we can call the xjb tool which is part of the Java SDK on the command line like this:

xjc calculator.xsd

As a result we get Java code that we can incorporate in our code base. Another option is to generate the Java code from our Maven build. This can be achieved by adding following Maven Plugin to your pom.


<plugin>
	<groupId>org.jvnet.jaxb2.maven2</groupId>
	<artifactId>maven-jaxb2-plugin</artifactId>
	<version>0.8.1</version>
	<executions>
		<execution>
			<goals>
				<goal>generate</goal>
			</goals>
		</execution>
	</executions>
	<configuration>
		<schemaDirectory>${project.basedir}/src/main/resources/xsd</schemaDirectory>
		<bindingDirectory>${project.basedir}/src/main/resources/xsd</bindingDirectory>  
                <generatePackage>net.pleus.services.calculator.api.model</generatePackage>
	</configuration>
</plugin>

As a result we get basic Java classes that represent the messages and types defined in our schema. If you want to affect the way the code is generated you can provide xjb binding files to customize the generated code. If you want for example use java.util.Calendar to be generated for an xsd:date type you can use the following binding:


<jaxb:bindings version="2.1"
    xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <jaxb:globalBindings generateElementProperty="false">
      <jaxb:javaType name="java.util.Calendar" xmlType="xsd:date"  
             parseMethod="javax.xml.bind.DatatypeConverter.parseDate"  
             printMethod="javax.xml.bind.DatatypeConverter.printDate">
      </jaxb:javaType>  
    </jaxb:globalBindings>   
</jaxb:bindings> 

Just drop the file jaxbbinding.xjb in the the same directory as your xsd file.

The foundation
We now have a simple Java class without any additional features:

JAXB comes with very useful plugins to pimp our generated code.

HashCode, equals, toString
If we want standard operations such as hashCode, equals or toString we can use the plugin org.jvnet.jaxb2_commons:jaxb2-basics.

This gives us:

Value Constructor
If we want value constructors, we can use the plugin org.jvnet.jaxb2_commons:jaxb2-value-constructor.

The result is:

Fluent APIs
Fluent APIs can be generated with the plugin net.java.dev.jaxb2-commons:jaxb-fluent-api.

This gives us a very nice fluent API to produce intuitive and readable code.

Bean Validation
One great aspect of schema first design is that one can nicely define types and constraints like tns:decimal9F2 shown in the listing at the top of this page. Wouldn’t it be nice if we could check those constraints in our code without additional effort? The plugin com.github.krasa:krasa-jaxb-tools generates JSR349 compliant bean validation annotations from our XSD types. After running the build we get annotated classes shown below for valueA which appears in the xsd as tns:decimal9F2:


@NotNull
@Digits(integer = 7, fraction = 2)
protected BigDecimal valueA;

To trigger the validation from your code we just need the following code snippet:


import javax.validation.*;

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Set<ConstraintViolation<PerformSimpleCalculationRequest>> violations = validatorFactory.getValidator().validate(request);
for(ConstraintViolation<PerformSimpleCalculationRequest> violation : violations){
  System.out.println("Violation: " + violation);
}

Javadoc
And finally it would be nice to have the documentation from within the XSD file in the generated Java code as well.
This can be achieved by the org.dpytel.jaxb:xjc-javadoc plugin.

If you have additional needs to manipulate the generated code, you can implement your own JAXB plugin which can be hooked into the build process. This gives you maximum flexibility and full control of the code generation.

The entire plugin configuration is shown here:



	org.jvnet.jaxb2.maven2
	maven-jaxb2-plugin
	0.8.1
	
		
			
				generate
			
		
	
	
		true
		>net.pleus.services.calculator.api.model
		
			-Xinheritance
			-XtoString
			-XhashCode
			-Xequals
			-Xvalue-constructor
			-Xfluent-api
                        -XJsr303Annotations
		
		${project.basedir}/src/main/resources/xsd
		${project.basedir}/src/main/resources/xsd
		
			
				org.jvnet.jaxb2_commons
				jaxb2-basics
				${jaxb2-basics.version}
			
			
				org.jvnet.jaxb2_commons
				jaxb2-value-constructor
				${jaxb2-value-constructor.version}
			
			
				net.java.dev.jaxb2-commons
				jaxb-fluent-api
				${jaxb-fluent-api.version}
			
			
     				com.github.krasa
				krasa-jaxb-tools
				${krasa-jaxb-tools.version}
			
                        
		                org.dpytel.jaxb
  		                xjc-javadoc
		                ${xjc-javadoc-version}
		        
		
	


In this post I’ve shown how to turn contracts into code on the Java platform easily. The contracts are 100% reusable, interoperable and cross platform, of instance on the .NET platform. Here you would use svcuitl.exe to turn the contract into code.

In part two I’m going to show how to turn contracts in into documentation.

Free Visual XML Schema Designer

Those of you who utilize a contract first design such as in Sustainable Service Design have the need to edit XML Schema files frequently. If you are like me you are using a plain text or xml editor, as it gives you the greatest flexibility to express exactly what you want.
But sometimes it is great to have a visual representation. For instance when you discuss business related interfaces with people from the business. Eclipse is somewhat limited in this regard as it does not show the structures and types in context.

Visual Studio.NET comes with a great XML Schema designer which is part of the professional edition for a long time. Now Microsoft offers the Visual Studio.NET Community Edition which is a fully featured Visual Studio including the XML Schema designer for free.

Here you can see how it looks like:

It works even if the types are spread into several XSDs. And it shows the documentation. You don’t even need a Visual Studio project. Just drop the Schema into the IDE and off you go.