javax.xml.bind.Binder.setEventHandler() Method



Description

The Javax.xml.bind.Binder.marshal(Object jaxbObject, XmlNode xmlNode) method allows an application to register a ValidationEventHandler.

The ValidationEventHandler will be called by the JAXB Provider if any validation errors are encountered during calls to any of the Binder unmarshal, marshal and update methods.

Calling this method with a null parameter will cause the Binder to revert back to the default default event handler.

Declaration

Following is the declaration for javax.xml.bind.Binder.setEventHandler(ValidationEventHandler handler) method

public abstract void setEventHandler(ValidationEventHandler handler)

Parameters

handler − the validation event handler.

Return Value

This method does not return any value.

Exception

JAXBException − if an error was encountered while setting the event handler.

Example

The following example shows the usage of javax.xml.bind.Binder.setEventHandler(ValidationEventHandler handler) method. To proceed, consider the following Student class which will be used to have objects for marshalling purpose −

package com.tutorialspoint;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
public class Student{
 
   String name;
   int age;
   int id;

   public String getName(){
      return name;
   }

   @XmlElement
   public void setName(String name){
      this.name = name;
   }

   public int getAge(){
      return age;
   }

   @XmlElement
   public void setAge(int age){
      this.age = age;
   }

   public int getId(){
      return id;
   }

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

Now let us create main class which will be used to unmarshal ie. convert Student.xml into an JAXB object. Here we will creat Binder object using JAXBContext because we can not create Binder object directly because it is an abstract class.

package com.tutorialspoint;

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Binder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class BinderDemo {
   public static void main(String[] args) {
  
      try {
         // we need a blank document to store final xml output
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder docBuilder = dbf.newDocumentBuilder();
         Document document = docBuilder.parse("Student.xml");
          
         // xml constant
         String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
         SchemaFactory sf = SchemaFactory.newInstance(schemaLanguage);
         File f = new File("Student.xsd");
         
         // create new schema
         Schema schema = sf.newSchema(f);
         
         // create JAXBContext which will be used to create a Binder
         JAXBContext jc = JAXBContext.newInstance(Student.class);

         // create binder object
         Binder<Node> binder = jc.createBinder();

         // set the property
         binder.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
         
         // get xml node
         Node xmlNode = document.getDocumentElement();
         
         // set schema for binder
         binder.setSchema(schema);
         
         // set validation event handler
         binder.setEventHandler(new StudentValidationEventHandler());
         
         // unmarshaling xml to JAXB object 
         Student st = (Student)binder.unmarshal(xmlNode);
         
         // finally print the marshalled object on stdout
         System.out.println("Name : "+st.getName());
         System.out.println("Age : "+st.getAge());
  
      }catch(Exception ex) {
         ex.printStackTrace();
      }
   }
}

Validation event handler class is created to detail any exception occured against the Student.xsd.

package com.tutorialspoint;

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;

public class StudentValidationEventHandler implements ValidationEventHandler {
   public boolean handleEvent(ValidationEvent event) {
      System.out.println("\nEvent");
      System.out.println("Severity:  " + event.getSeverity());
      System.out.println("Message:  " + event.getMessage());
      System.out.println("Linked Exception:  " + event.getLinkedException());
      System.out.println("LOCATOR");
      System.out.println("   Line Number:  " + event.getLocator().getLineNumber());
      System.out.println("   Column Number:  " + event.getLocator().getColumnNumber());
      System.out.println("   Offset:  " + event.getLocator().getOffset());
      System.out.println("   Object:  " + event.getLocator().getObject());
      System.out.println("   Node:  " + event.getLocator().getNode());
      System.out.println("   Url:  " + event.getLocator().getURL());
      return true;
   }
}

To set event validation handler we need to set the schema. Below is the Student.xsd

  <?xml version = "1.0" encoding = "utf-8"?>
<xs:schema attributeFormDefault = "unqualified" elementFormDefault = "qualified" 
xmlns:xs = "http://www.w3.org/2001/XMLSchema">
   <xs:element name = "student">
      <xs:complexType>
         <xs:sequence>
            <xs:element name = "age" type = "xs:unsignedByte" />
            <xs:element name = "name" type = "xs:string" />
         </xs:sequence>
         <xs:attribute name = "id" type = "xs:unsignedByte" use = "required" />
      </xs:complexType>
   </xs:element>
</xs:schema>

The input student.xml is as follows. This XML will be provided as input.

<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<student id = "10">
   <age>12</age>
   <name>Malik</name>
</student>

Before we proceed for compilation, we need to make sure that that we download JAXB2.xxx.jar and put it in our CLASSPATH. Once setup is ready, let us compile and run the above program, this will produce the following result −

Event
Severity:  1
Message:  Not a number: Age 12
Linked Exception:  java.lang.NumberFormatException: Not a number: Age 12
LOCATOR
   Line Number:  -1
   Column Number:  -1
   Offset:  -1
   Object:  null
   Node:  [age: null]
   Url:  null

Event
Severity:  2
Message:  cvc-datatype-valid.1.2.1: 'Age 12' is not a valid value for 'integer'.
Linked Exception:  org.xml.sax.SAXParseException; 
cvc-datatype-valid.1.2.1: 'Age 12' is not a valid value for 'integer'.
LOCATOR
   Line Number:  -1
   Column Number:  -1
   Offset:  -1
   Object:  null
   Node:  [age: null]
   Url:  null

Event
Severity:  2
Message:  cvc-type.3.1.3: The value 'Age 12' of element 'age' is not valid.
Linked Exception:  org.xml.sax.SAXParseException; 
cvc-type.3.1.3: The value 'Age 12' of element 'age' is not valid.
LOCATOR
   Line Number:  -1
   Column Number:  -1
   Offset:  -1
   Object:  null
   Node:  [age: null]
   Url:  null
Name : Malik
Age : 0
javax_xml_bind_binder.htm
Advertisements