Validate object against xsd / generated object

I have an application where I have generated Java classes from an xsd schema. I also have a rest service using jax-rs. I need to validate the input to the POST methods, to ensure that comply with the rules set in the xsd schema.

@POST
@Path("/person/add")
public void addPerson(Person person) {

    //Need to validate Person object 

    daoManager.addPersonToDB(person);
}

The Person object is a class generated from the xsd. Can I assume that the object complies with the xsd, or will I have to validate the object? In that case, how can I validate?

I know this is a newbie question, but I hope someone can help.

Answer

I haven’t tried myself, but I think the following code would work.

JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();

according to your namespace, use

marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "yourXSD.xsd");

or

marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "yourXSD.xsd");

and then marshal the person instance, if no exception, that means the person instance is fine. Otherwise, it’s not.


Oh, I forgot on thing. Before you marshal it, remember to setSchema()

    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("your.xsd"));

    marshaller.setSchema(schema);
    marshaller.setEventHandler(new ValidationEventHandler() {
      public boolean handleEvent(ValidationEvent event) {
        System.out.println(event);
        return false; //to stop the marshal if anything happened
      }
    });

Leave a Reply

Your email address will not be published. Required fields are marked *