开发者

JAXB 2.0 Validation not working

i am working on JAXB 2.0 and currently struck on the validation part as its not working as expected. below is the validation code

public void validateXMLToSchema(Unmarshaller ummarshaller,String xsdFileName) throws SAXException, JAXBException{
    System.out.println(getClass().getResource(DEFAULT_XSD_NAME).toString());
    Schema schema;
    SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    if(null==xsdFileName)
        schema=schemaFactory.newSchema(getClass().getResource(DEFAULT_XSD_NAME));

    else
        schema=schemaFactory.newSchema(new File(xsdFileName));

    ummarshaller.setSchema(schema);
    ummarshaller.setEventHandler( new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent validationevent) {
            if(validationevent.getS开发者_JAVA百科everity()==ValidationEvent.FATAL_ERROR || validationevent.getSeverity()==ValidationEvent.ERROR || validationevent.getSeverity()==ValidationEvent.WARNING){
                ValidationEventLocator  locator = validationevent.getLocator();
                log.info("Line:Col[" + locator.getLineNumber()
                        + ":" + locator.getColumnNumber()
                        + "]:" + validationevent.getMessage());
            }
            return true;
        }
    });

}

and here is the call to the method

Destination destination=new Destination();
    try {
         destination=(Destination)unmarshal(Destination.class,new FileInputStream(new File("C:/Users/Raisonne/Desktop/jaxb/jaxb-ri-20101119/bin/destination.xml")));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    System.out.println(destination.getName());

}

public static <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException, SAXException {
String packageName = docClass.getPackage().getName();
JAXBContext jc = JAXBContext.newInstance( packageName );
Unmarshaller u = jc.createUnmarshaller();
XMLValidator xmlValidator=new XMLValidator();
xmlValidator.validateXMLToSchema(u, null);

i have few fields as required fields as per XSD but even removing them it shd give me the error while its not giving anything and parsing my xml file in to the corresponding object can any one point whats going wrong?

here is the part of XSD

    <xs:element name="destination" type="Destination"/>
  <xs:complexType name="Destination">
    <xs:sequence>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="destinationID" type="xs:string" minOccurs="0"/>
      <xs:element name="shortDescription" type="xs:string" minOccurs="0"/>
      <xs:element name="longDescription" type="xs:string" minOccurs="0"/>
      <xs:element name="stateID" type="xs:string"/>
      <xs:element name="typeCode" type="xs:int"/>
      <xs:element name="countryCode" type="xs:string"/>
      <xs:element name="categories" type="xs:string"/>
      <xs:element name="transport" type="Transport" minOccurs="0" maxOccurs="1"/>
      <xs:element name="culture" type="Culture" minOccurs="0" maxOccurs="1"/>
      <xs:element name="events" type="Events" minOccurs="0" maxOccurs="1"/>
      <xs:element name="placesToVisit" type="PlacesToVisit" minOccurs="0" maxOccurs="1"/>
      <xs:element name="contacts" type="Contact" minOccurs="0" maxOccurs="1"/>
      <xs:element name="addresses" type="address" minOccurs="0" maxOccurs="1"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

and the Java file generated

@XmlElement(required = true)
protected String name;
protected String destinationID;
protected String shortDescription;
protected String longDescription;
@XmlElement(required = true)
protected String stateID;

i was removing stateID from the xml file but still no alarm in validation part

thanks in advance


Your code fragment is a bit hard to follow, is an unmarshal actually occurring? You may need to add the last line to your unmarshal method:

public static <T> T unmarshal( Class<T> docClass, InputStream inputStream ) throws JAXBException, SAXException {
    String packageName = docClass.getPackage().getName();
    JAXBContext jc = JAXBContext.newInstance( packageName );
    Unmarshaller u = jc.createUnmarshaller();
    XMLValidator xmlValidator=new XMLValidator();
    xmlValidator.validateXMLToSchema(u, null);
    u.unmarshal(inputStream);
}


According to this line

xmlValidator.validateXMLToSchema(u, null);

you are not giving the XSD file name to XmlValidator. It should be something like

xmlValidator.validateXMLToSchema(u, "/opt/projects/myschema.xsd");

Edit: Well this is how I managed to do it and it's working perfectly:

void validate(MyRequest requestParameters) throws IllegalArgumentException,MalformedURLException,SAXException {
    try {
        JAXBContext context = JAXBContext.newInstance(MyRequest.class.getPackage().getName());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setSchema(getSchema());
        JAXBElement<MyRequest> rootElement = new JAXBElement<SearchCustomersRequest>(new QName("http://mysite.com/xsd/myproject/", "MyRequest"),
                        MyRequest.class, requestParameters);
        marshaller.marshal(rootElement, new DefaultHandler());
        log.debug("Validation successful");
    } catch (JAXBException e) {
        throw new IllegalArgumentException("Invalid request parameters: " + e.toString(), e);
    }
}

private Schema getSchema() throws MalformedURLException, SAXException {
    if (schema == null) {
        SchemaFactory factory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = new URL("http://mysite.com/xsd/myproject/schema-1.0.xsd");
        schema = factory.newSchema(schemaUrl);
    }
    return schema;
}


Really strange when i changed my code to this

public class UnMarshallXML {

/**
 * @param args
 * @throws SAXException 
 */
public static void main(String[] args) throws SAXException {
    Destination destination=new Destination();
    try {
         destination=(Destination)unmarshal(Destination.class,new FileInputStream(new File("C:/Users/Raisonne/Desktop/jaxb/jaxb-ri-20101119/bin/destination.xml")));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    System.out.println(destination.getName());

}

public static <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException, SAXException {
String packageName = docClass.getPackage().getName();
System.out.println(packageName);
JAXBContext jc = JAXBContext.newInstance( packageName );
Unmarshaller u = jc.createUnmarshaller();
SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema=schemaFactory.newSchema(new File("C:/Users/Raisonne/Desktop/jaxb/jaxb-ri-20101119/bin/destination.xsd"));

u.setSchema(schema);
u.setEventHandler(
        new ValidationEventHandler() {
            // allow unmarshalling to continue even if there are errors
            public boolean handleEvent(ValidationEvent ve) {
                // ignore warnings
                if (ve.getSeverity() != ValidationEvent.WARNING) {
                    ValidationEventLocator vel = ve.getLocator();
                    System.out.println(
                            "Line:Col[" + vel.getLineNumber()
                            + ":" + vel.getColumnNumber()
                            + "]:" + ve.getMessage());
                }

                return true;
            }
        });
// XMLValidator xmlValidator=new XMLValidator();
//xmlValidator.validateXMLToSchema(u, null,inputStream);
@SuppressWarnings("unchecked")
JAXBElement<T> doc = (JAXBElement<T>)u.unmarshal( inputStream );
return doc.getValue();

}

}

everything started working like charm..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜