vikas27
vikas27

Reputation: 573

XSD Validation Using Schema Issue

I have a xml file like

<root>
  <requestId>1</requestId>
  <subRequest>
    <id>11</id>
    <date>18-02-2015</date>
  </subRequest>
  <subRequest>
    <id>12</id>
    <date>19-02-2015</date>
  </subRequest>
  .
  .
</root>

I have a XSD file which I cannot change and in that file the date have to be in some format. And there can be 1000 entries of "subRequest" tag. I created a schema validation to check the format.

So my problem is out of these 1000 entries, if there is only 2 entries whose date format is incorrect, how can I know id's of these 2 entries.

I am checking this when I am converting this xml into bean using JAXB(unmarshaller). I used schema validations and the validator.getLocalizedMessage() give null for both object and node. I can see only lineNumber and the general message about the issue format.

Upvotes: 2

Views: 1351

Answers (3)

Dennis
Dennis

Reputation: 2175

I know that you are searching for a solution based on JAXB. However, if you just want to find that specific error, you can also use a simple SAXParser to track it down quickly. Maybe it helps you to find what causes the error in the first place.

EDIT

I added a field to the DefaultHandler that allows you to get the subrequest id provoking the error. As I said, this should help to track down the error, it doesn't win a prize for beauty.

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;

public class RequestParser {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {

        Schema schema = null;

        try {
            String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
            SchemaFactory factory = SchemaFactory.newInstance(language);
            schema = factory.newSchema(new File("YOUR_SCHEMA.xsd"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setSchema(schema);

        SAXParser parser = spf.newSAXParser();

        parser.parse(new File("YOUR_DOCUMENT.xml"), new DefaultHandler(){

            String currentNodeQName = "";
            String currentSubrequestId = "";

            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                currentNodeQName = qName;
            }

            public void characters(char[] ch, int start, int length) throws SAXException {
                if (currentNodeQName.equals("id")) {
                    currentSubrequestId = new String(ch, start, length);
                }
            }

            public void warning(SAXParseException e) throws SAXException {
                System.out.println("Warning in subrequest with id " + currentSubrequestId);
                e.printStackTrace();
            }

            public void error(SAXParseException e) throws SAXException {
                System.out.println("Error in subrequest with id: " + currentSubrequestId);
                e.printStackTrace();
            }

            public void fatalError(SAXParseException e) throws SAXException {
                System.out.println("Fatal error in subrequest with id " + currentSubrequestId);
                e.printStackTrace();
            }
        });
    }
}

You can also set a breakpoint at these three exceptional blocks, which will give you even more info about the error at hand.

EDIT 2

Sample output:

Error in subrequest with id 12
org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: '19-02-2015' is not a valid value for 'date'.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:423)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3188)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.elementLocallyValidType(XMLSchemaValidator.java:3103)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.processElementContent(XMLSchemaValidator.java:3013)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleEndElement(XMLSchemaValidator.java:2156)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.endElement(XMLSchemaValidator.java:824)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1789)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2950)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:647)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:513)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:815)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:744)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:128)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1208)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:543)
    at javax.xml.parsers.SAXParser.parse(SAXParser.java:395)
    at javax.xml.parsers.SAXParser.parse(SAXParser.java:331)
    at so28836220.RequestParser.main(RequestParser.java:43)

Upvotes: 1

bdoughan
bdoughan

Reputation: 149047

You could do the following:

Unmarshaller.Listener & ValidationEventHandler

You could create a combination Unmarshaller.Listener and ValidationEventHandler for this use case.

import javax.xml.bind.*;

public class SubRequestValidator extends Unmarshaller.Listener implements ValidationEventHandler {

    private SubRequest subRequest;

    @Override
    public void beforeUnmarshal(Object target, Object parent) {
        if(target.getClass() == SubRequest.class) {
            subRequest = (SubRequest) target;
        } else {
            subRequest = null;
        }
    }

    public SubRequest getSubRequest() {
        return subRequest;
    }

    @Override
    public boolean handleEvent(ValidationEvent validationEvent) {
        if(subRequest != null) {
            System.out.println(subRequest.getId());
            System.out.println(validationEvent.getMessage());
        }
        return validationEvent.getSeverity() != ValidationEvent.FATAL_ERROR;
    }

}

Then you would set the both on your Unmarshaller in addition to an instance of Schema.

    SubRequestValidator subRequestValidator = new SubRequestValidator();
    unmarshaller.setListener(subRequestValidator);
    unmarshaller.setEventHandler(subRequestValidator);

Demo Code

Below is some supporting material to complete the example:

XML Schema (schema.xsd)

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
    <element name="root">
        <complexType>
            <sequence>
                <element name="requestId" type="int"/>
                <element name="subRequest" maxOccurs="unbounded">
                    <complexType>
                        <sequence>
                            <element name="id" type="int"/>
                            <element name="date" type="date"/>
                        </sequence>
                    </complexType>
                </element>
            </sequence>
        </complexType>
    </element>
</schema>

XML (input.xml)

<root>
  <requestId>1</requestId>
  <subRequest>
    <id>11</id>
    <date>2015-02-18</date>
  </subRequest>
  <subRequest>
    <id>12</id>
    <date>WRONG</date>
  </subRequest>
  <subRequest>
    <id>13</id>
    <date>2015-02-19</date>
  </subRequest>
</root>

Root

import java.util.*;
import javax.xml.bind.annotation.*;

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

    private int requestId;

    @XmlElement(name="subRequest")
    private List<SubRequest> subRequests;

}

SubRequest

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class SubRequest {

    private int id;
    private String date;

    public int getId() {
        return id;
    }

}

Demo

import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import javax.xml.validation.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
        Schema schema = sf.newSchema(new File("src/forum28584265/schema.xsd")); 
        unmarshaller.setSchema(schema);

        SubRequestValidator subRequestValidator = new SubRequestValidator();
        unmarshaller.setListener(subRequestValidator);
        unmarshaller.setEventHandler(subRequestValidator);

        File xml = new File("src/forum28584265/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);
    }

}

Output

12
cvc-datatype-valid.1.2.1: 'WRONG' is not a valid value for 'date'.
Exception in thread "main" javax.xml.bind.UnmarshalException
 - with linked exception:
[org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: 'WRONG' is not a valid value for 'date'.]
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:514)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:215)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:184)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:151)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:169)
    at forum28584265.Demo.main(Demo.java:23)
Caused by: org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: 'WRONG' is not a valid value for 'date'.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:423)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3188)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.elementLocallyValidType(XMLSchemaValidator.java:3103)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.processElementContent(XMLSchemaValidator.java:3013)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleEndElement(XMLSchemaValidator.java:2156)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.endElement(XMLSchemaValidator.java:824)
    at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.endElement(ValidatorHandlerImpl.java:566)
    at com.sun.xml.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.endElement(ValidatingUnmarshaller.java:101)
    at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.endElement(SAXConnector.java:156)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:604)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1789)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2950)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:647)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:513)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:815)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:744)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:128)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1208)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:543)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:211)
    ... 6 more

Upvotes: 3

bdoughan
bdoughan

Reputation: 149047

You could do the following:

Unmarshaller.Listener

You could create an Unmarshaller.Listener to keep track of the current SubRequest being unmarshalled.

import javax.xml.bind.Unmarshaller;

public class SubRequestListener extends Unmarshaller.Listener {

    private SubRequest subRequest;

    @Override
    public void beforeUnmarshal(Object target, Object parent) {
        if(target.getClass() == SubRequest.class) {
            subRequest = (SubRequest) target;
        } else {
            subRequest = null;
        }
    }

    public SubRequest getSubRequest() {
        return subRequest;
    }

}

XmlAdapter

Then implement an XmlAdapter to validate the content of the Date property. In this example I assume you are storing it as a String. If you are storing it as something else (i.e. Date) then change the XmlAdapter<String, String> to XmlAdapter<Date, String>. This XmlAdapter references the Unmarshaller.Listener to get the instance of SubRequest.

import java.text.SimpleDateFormat;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateValidator extends XmlAdapter<String, String> {

    private SubRequestListener subRequestListener;

    public DateValidator() {
        this.subRequestListener = new SubRequestListener();
    }

    public DateValidator(SubRequestListener subRequestListener) {
        this.subRequestListener = subRequestListener;
    }

    @Override
    public String marshal(String value) throws Exception {
        return value;
    }

    @Override
    public String unmarshal(String value) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        try {
            sdf.applyPattern(value);
        } catch(IllegalArgumentException e) {
            SubRequest subRequest = subRequestListener.getSubRequest();
            System.out.println(subRequest.getId());
        }
        return value;
    }

}

SubRequest

Below is how you reference the XmlAdapter.

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlAccessorType(XmlAccessType.FIELD)
public class SubRequest {

    private int id;

    @XmlJavaTypeAdapter(DateValidator.class)
    private String date;

    public int getId() {
        return id;
    }

}

Demo

Below is some demo code on how to set things up.

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();

        SubRequestListener unmarshallerListener = new SubRequestListener();
        unmarshaller.setListener(unmarshallerListener);

        DateValidator dateAdapter = new DateValidator(unmarshallerListener);
        unmarshaller.setAdapter(dateAdapter);

        File xml = new File("input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root,  System.out);
    }

}

Upvotes: 4

Related Questions