1 22 package org.jboss.test.xml; 23 24 import java.io.ByteArrayInputStream ; 25 import java.io.StringReader ; 26 import javax.xml.parsers.SAXParserFactory ; 27 import javax.xml.parsers.SAXParser ; 28 import org.xml.sax.SAXException ; 29 import org.xml.sax.SAXParseException ; 30 import org.xml.sax.InputSource ; 31 import org.xml.sax.EntityResolver ; 32 import org.xml.sax.helpers.DefaultHandler ; 33 import org.jboss.xb.binding.JBossXBRuntimeException; 34 35 39 public class Validator 40 { 41 public static void assertValidXml(final String xsd, String xml) 42 { 43 assertValidXml(xsd, xml, null); 44 } 45 46 public static void assertValidXml(String xml, final EntityResolver resolver) 47 { 48 assertValidXml(null, xml, resolver); 49 } 50 51 private static void assertValidXml(final String xsd, String xml, final EntityResolver resolver) 52 { 53 SAXParserFactory factory = SAXParserFactory.newInstance(); 54 factory.setValidating(true); 55 factory.setNamespaceAware(true); 56 SAXParser parser = null; 57 try 58 { 59 parser = factory.newSAXParser(); 60 } 61 catch(Exception e) 62 { 63 throw new IllegalStateException ("Failed to instantiate a SAX parser: " + e.getMessage()); 64 } 65 66 try 67 { 68 parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema", true); 69 } 70 catch(SAXException e) 71 { 72 throw new IllegalStateException ("Schema validation feature is not supported by the parser: " + e.getMessage()); 73 } 74 75 try 76 { 77 parser.parse(new ByteArrayInputStream (xml.getBytes()), 78 new DefaultHandler () 79 { 80 public void warning(SAXParseException e) 81 { 82 } 83 84 public void error(SAXParseException e) 85 { 86 throw new JBossXBRuntimeException("Error", e); 87 } 88 89 public void fatalError(SAXParseException e) 90 { 91 throw new JBossXBRuntimeException("Fatal error", e); 92 } 93 94 public InputSource resolveEntity(String publicId, String systemId) 95 { 96 if(resolver != null) 97 { 98 try 99 { 100 return resolver.resolveEntity(publicId, systemId); 101 } 102 catch(Exception e) 103 { 104 throw new IllegalStateException ("Failed to resolveEntity " + systemId + ": " + systemId); 105 } 106 } 107 else 108 { 109 return new InputSource (new StringReader (xsd)); 110 } 111 } 112 } 113 ); 114 } 115 catch(Exception e) 116 { 117 throw new JBossXBRuntimeException("Parsing failed.", e); 118 } 119 } 120 } 121 | Popular Tags |