views:

107

answers:

2

Hi, What I thought was going to be a simple problem turns out to be quite a head scratcher.

I am currently using JAXB 2 to generate code from an XSD on which I have no control. I need to access the constraints from the schemas so I can apply some logic and guard code when setting values in these objects. Validation in bulk simply will not do. In most cases I can simply truncate the string and all will be good. For this I need to get the length that was declared in the XSD in order to apply it in the guard code and keep this layer generic. The alternative is to copy and hard code the lengths but frankly if there was a better way to do this I would really appreciate.

I speak of string length here but this applies to all facets declarable in an XSD.

Suggestions, Code samples and links welcome, basically anything that would help me NOT hard code the data in the classes.

Thanks

A: 

Unfortunately, there is currently nothing in the JAXB spec to handle this. You could add Bean Validation (JSR-303) annotations to your model manually and use those mechanisms to validate. Not sure if this helps.

Blaise Doughan
+2  A: 

I was faced with a similar problem and the best solution I found was to write my own XJC plugin. An XJC plugin has access to both the XML schema and the generated classes, so it seemed like the easiest way to get at the restriction information. My plugin added an annotation to any field in the generated class that had restrictions applied to it in the schema. For instance, an element like

<xs:element name="text">
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:maxLength value="20" />
        </xs:restriction>
    </xs:simpleType>
</xs:element>

would appear as

@XmlRestrictions(maxLength = 20)
protected String text;

in the generated class file. Then, you could use reflection to extract the restriction information from the field.

The documentation for creating a plugin isn't too great, but I found this article useful. Take a look at the source code for the Default Value Plugin to see how to drill down into XJC's in-memory representation of the XML schema and generated class structure. The JAXB, XSOM, and CodeModel API's will also be helpful.

Charles Hellstrom
yep that sounds quite reasonable approach though it will require a bit more work than I am ready to put in at the moment. I will try your suggestion later when I come back to the project in question. I<ll let you know how it turns out when I get there.
Newtopian