Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JAXB to support schemas with minor variations

The Situation

I need to support generating XML documents based on schemas that vary only slightly between each other. Specifically, the schemas that I need to support are based on industry standards that change slightly over time and vendors may make their own customized version of them.

The Problem

I was intending to use JAXB 2 (from Metro) with inheritance as a solution. I expected the package structure to end up something like this:

    com.company.xml.schema.v1
    com.company.xml.schema.v2
    com.company.xml.schema.v2.vendorxyz

Where the classes in the v2 package would simply extend the classes in the v1 package and override as necessary. Unfortunately, that plan ended up being impossible since subclasses cannot overwrite the annotations in parent classes (see here). For example, if an attribute in a schema was renamed between versions, then the v2 element class would have to completely re-implement the element without inheriting from the v1.

So that leaves me with only two options as far as I can tell

Option 1

Create a "base" package for each schema type, annotate the element classes in that package with @XmlAccessorType(XmlAccessType.NONE), and remove all other annotations. Then, in each versioned package create classes that subclass the corresponding class in the "base" package and add all the required annotations. This solution does give me a little help in the inheritance realm, but code duplication is huge and it would be a challenge to maintain.

Option 2

Don't use JAXB. I really don't like this solution since I'd also like to work with JAX-RS/JAX-WS.

Questions

  • How should I be using JAXB in order to support multiple schemas with minor variations, without a bunch of code duplication?
  • Is there a different technology combination I should be looking at?

EDIT

The solution below from Blaise worked perfectly for most of our schemas which were just a minor translation of each other with generally the same data. However, we ran into a problem in cases where it made more sense to use inheritance with package names for versioning. For Example:

com.company.xml.schema.v1.ElementA
com.company.xml.schema.v2.ElementA

(where v2.ElementA extends v1.ElementA)

Using MOXy's OXM in this case stumbles across a bug and the workaround can be found here (with the solution provided by Blaise, no less!)

like image 278
Terence Avatar asked Feb 23 '12 19:02

Terence


People also ask

Is JAXB memory efficient?

Generally JAXB is quite efficient and you shouldn't care about memory issues unless your application handles XMLs of very large size.

What is JAXB used for?

JAXB simplifies access to an XML document from a Java program by presenting the XML document to the program in a Java format. The first step in this process is to bind the schema for the XML document into a set of Java classes that represents the schema.

How do you auto generate JAXB classes?

Open a command prompt. Run the JAXB schema compiler, xjc command from the directory where the schema file is located. The xjc schema compiler tool is located in the app_server_root \bin\ directory. Use the generated JAXB objects within a Java application to manipulate XML content through the generated JAXB classes.


1 Answers

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

You could use the external binding document in EclipseLink JAXB to map the variations among XML Schemas.

Vendor 1

You could use the standard JAXB annotations to map one of the vendors:

package forum9419732;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlAttribute
    private int id;

    private String lastName;
    private String firstName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

Vendor 2

We will use MOXy's external metadata to customize the metadata provided by annotations. In the document (oxm-v2.xml) below we will map the firstName and lastName properties to XML Attributes:

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum9419732">
    <java-types>
        <java-type name="Customer">
            <java-attributes>
                <xml-attribute java-attribute="firstName"/>
                <xml-attribute java-attribute="lastName"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

Vendor 3

Again we will use MOXy's external binding document (oxm-v3.xml) to override the annotations. This time we will make the id property an XML element.

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum9419732">
    <java-types>
        <java-type name="Customer">
            <java-attributes>
                <xml-element java-attribute="id" name="identifier"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

Demo

The sample code below demonstrates to specify the external metadata. Note how I introduced a fourth vendor to show that the external metadata documents can be combined.

package forum9419732;

import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;

public class Demo {

    public static void main(String[] args) throws JAXBException {
        Customer customer = new Customer();
        customer.setId(123);
        customer.setFirstName("Jane");
        customer.setLastName("Doe");

        // VENDOR 1
        JAXBContext jcV1 = JAXBContext.newInstance(Customer.class);
        marshal(jcV1, customer);

        // VENDOR 2
        Map<String, Object> propertiesV2 = new HashMap<String, Object>(1);
        propertiesV2.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum9419732/oxm-v2.xml");
        JAXBContext jcV2 = JAXBContext.newInstance(new Class[] {Customer.class}, propertiesV2);
        marshal(jcV2, customer);

        // VENDOR 3
        Map<String, Object> propertiesV3 = new HashMap<String, Object>(1);
        propertiesV3.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum9419732/oxm-v3.xml");
        JAXBContext jcV3 = JAXBContext.newInstance(new Class[] {Customer.class}, propertiesV3);
        marshal(jcV3, customer);

        // VENDOR 4
        Map<String, Object> propertiesV4 = new HashMap<String, Object>(1);
        List<String> oxmV4 = new ArrayList<String>(2);
        oxmV4.add("forum9419732/oxm-v2.xml");
        oxmV4.add("forum9419732/oxm-v3.xml");
        propertiesV4.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, oxmV4);
        JAXBContext jcV4 = JAXBContext.newInstance(new Class[] {Customer.class}, propertiesV4);
        marshal(jcV4, customer);
    }

    private static void marshal(JAXBContext jc, Customer customer) throws JAXBException {
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
        System.out.println();
    }

}

Output

Below is the output from each of the vendors. Remember that the same instance of Customer was used to make each of these XML documents.

<?xml version="1.0" encoding="UTF-8"?>
<customer id="123">
   <lastName>Doe</lastName>
   <firstName>Jane</firstName>
</customer>

<?xml version="1.0" encoding="UTF-8"?>
<customer id="123" lastName="Doe" firstName="Jane"/>

<?xml version="1.0" encoding="UTF-8"?>
<customer>
   <identifier>123</identifier>
   <lastName>Doe</lastName>
   <firstName>Jane</firstName>
</customer>

<?xml version="1.0" encoding="UTF-8"?>
<customer lastName="Doe" firstName="Jane">
   <identifier>123</identifier>
</customer>

For More Information

  • http://blog.bdoughan.com/search/label/jaxb.properties
  • http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html
  • http://blog.bdoughan.com/2011/09/mapping-objects-to-multiple-xml-schemas.html
like image 52
bdoughan Avatar answered Sep 18 '22 18:09

bdoughan