Java to XSD Example

Here's the scenario.  You've just built a nice fancy endpoint and you're asking other groups to consume it.  Problem is your data model is complex and posting a big messy object is tedious and difficult.  You could move your data model outside your app, but that still locks them to whatever language you've written.  

How about we export our data model to a schema and send them the file so they can generate the objects in the langauge of their choice?  Sounds good to me.  Let's do this with JaxB.  In our example we'll build a pizza shop API which allows consumer to send a pizza request and then forward them a recipt.

View Source on Github

Notice we've annoated the Pizza class and it's children with XmlElement annoations.  This tells JaxB we will be converting these to xml.

@Data
@XmlType
@XmlRootElement
public class Pizza {

    @XmlElement
    String name;

    @XmlElement
    int size;

    @XmlElement
    List<Topping> toppings;

    @XmlElement
    Customer customer;

}

Checkout the jaxb2-maven-plugin inside of the api pom.xml.  Here you can see we're pointing at our Pizza model.

<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>jaxb2-maven-plugin</artifactId>
	<version>2.2</version>
	<executions>
		<execution>
			<id>schemagen</id>
			<goals>
				<goal>schemagen</goal>
			</goals>
		</execution>
	</executions>
	<configuration>
		<sources>
			<source>src/main/java/net/largepixels/jaxb/example01/pizza/api/pizzaapi/model</source>
		</sources>
	</configuration>
</plugin>

Run "mvn jaxb2:schemagen" from the pizza-api root or the following from your IDE.

Generate with JaxB

Now that you've got your XSD file.  You can grab it out of your target folder and mail it to that development team working against your API. 

Clients Generate Code

Now your clients can configure their projects to generate source code from your XSD file.  They could do it with a pom.xml like this...

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.2</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <sources>
            <source>src/main/resources/schema1.xsd</source>
        </sources>
    </configuration>
</plugin>

From here they can run a "mvn clean install" and their target folder will now contain the generated sources.  

Note:  Running mvn clean install, then importing the project into your IDE is the easiest way to ensure your IDE picks up the generated sources.  

Now you can use REST frameworks like "Rest Template" to easily exchange data between systems and without hard dependencies between them!  In fact your team could keep incrementing the version of it's software (and releasing it if the model doesn't change), and clients interacting with your API wouldn't even care. 

JaxB Tutorial