Search in sources :

Example 76 with SchemaFactory

use of javax.xml.validation.SchemaFactory in project opennms by OpenNMS.

the class XmlTest method validateJaxbXmlAgainstSchema.

@Test
public void validateJaxbXmlAgainstSchema() throws Exception {
    final String schemaFile = getSchemaFile();
    if (schemaFile == null) {
        LOG.warn("Skipping validation.");
        return;
    }
    LOG.debug("Validating against XSD: {}", schemaFile);
    javax.xml.bind.Unmarshaller unmarshaller = JaxbUtils.getUnmarshallerFor(getSampleClass(), null, true);
    final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final Schema schema = factory.newSchema(new StreamSource(schemaFile));
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(final ValidationEvent event) {
            LOG.warn("Received validation event: {}", event, event.getLinkedException());
            return false;
        }
    });
    try {
        final InputSource inputSource = new InputSource(getSampleXmlInputStream());
        final XMLFilter filter = JaxbUtils.getXMLFilterForClass(getSampleClass());
        final SAXSource source = new SAXSource(filter, inputSource);
        @SuppressWarnings("unchecked") T obj = (T) unmarshaller.unmarshal(source);
        assertNotNull(obj);
    } finally {
        unmarshaller.setSchema(null);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) ValidationEventHandler(javax.xml.bind.ValidationEventHandler) InputSource(org.xml.sax.InputSource) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) XMLFilter(org.xml.sax.XMLFilter) SAXSource(javax.xml.transform.sax.SAXSource) ValidationEvent(javax.xml.bind.ValidationEvent) Test(org.junit.Test)

Example 77 with SchemaFactory

use of javax.xml.validation.SchemaFactory in project opennms by OpenNMS.

the class JaxbUtils method getValidatorFor.

private static Schema getValidatorFor(final Class<?> clazz) {
    LOG.trace("finding XSD for class {}", clazz);
    if (m_schemas.containsKey(clazz)) {
        return m_schemas.get(clazz);
    }
    final List<Source> sources = new ArrayList<Source>();
    final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    for (final String schemaFileName : getSchemaFilesFor(clazz)) {
        InputStream schemaInputStream = null;
        try {
            if (schemaInputStream == null) {
                final File schemaFile = new File(System.getProperty("opennms.home") + "/share/xsds/" + schemaFileName);
                if (schemaFile.exists()) {
                    LOG.trace("Found schema file {} related to {}", schemaFile, clazz);
                    schemaInputStream = new FileInputStream(schemaFile);
                }
                ;
            }
            if (schemaInputStream == null) {
                final File schemaFile = new File("target/xsds/" + schemaFileName);
                if (schemaFile.exists()) {
                    LOG.trace("Found schema file {} related to {}", schemaFile, clazz);
                    schemaInputStream = new FileInputStream(schemaFile);
                }
                ;
            }
            if (schemaInputStream == null) {
                final URL schemaResource = Thread.currentThread().getContextClassLoader().getResource("xsds/" + schemaFileName);
                if (schemaResource == null) {
                    LOG.debug("Unable to load resource xsds/{} from the classpath.", schemaFileName);
                } else {
                    LOG.trace("Found schema resource {} related to {}", schemaResource, clazz);
                    schemaInputStream = schemaResource.openStream();
                }
            }
            if (schemaInputStream == null) {
                LOG.trace("Did not find a suitable XSD.  Skipping.");
                continue;
            } else {
                sources.add(new StreamSource(schemaInputStream));
            }
        } catch (final Throwable t) {
            LOG.warn("an error occurred while attempting to load {} for validation", schemaFileName);
            continue;
        }
    }
    if (sources.size() == 0) {
        LOG.debug("No schema files found for validating {}", clazz);
        return null;
    }
    LOG.trace("Schema sources: {}", sources);
    try {
        final Schema schema = factory.newSchema(sources.toArray(EMPTY_SOURCE_LIST));
        m_schemas.put(clazz, schema);
        return schema;
    } catch (final SAXException e) {
        LOG.warn("an error occurred while attempting to load schema validation files for class {}", clazz, e);
        return null;
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) XmlSchema(javax.xml.bind.annotation.XmlSchema) Schema(javax.xml.validation.Schema) ArrayList(java.util.ArrayList) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) FileInputStream(java.io.FileInputStream) URL(java.net.URL) SAXException(org.xml.sax.SAXException) File(java.io.File)

Example 78 with SchemaFactory

use of javax.xml.validation.SchemaFactory in project opennms by OpenNMS.

the class JaxbUtilsTest method testMarshalEvent.

@Test
public void testMarshalEvent() throws Exception {
    final Event e = getEvent();
    final String xml = JaxbUtils.marshal(e);
    assertTrue(xml.contains("JaxbUtilsTest"));
    LOG.debug("event = {}", e);
    LOG.debug("xml = {}", xml);
    final StringWriter sw = new StringWriter();
    JaxbUtils.marshal(e, sw);
    assertEquals(sw.toString(), xml);
    final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final InputStream is = this.getClass().getResourceAsStream("/xsds/event.xsd");
    // if this is null, it's because Eclipse can be confused by "classifier" test dependencies like opennms-model-*-xsds
    // it only works if opennms-model is *not* pulled into eclipse (go figure)
    Assume.assumeNotNull(is);
    LOG.debug("Hooray!  We have an XSD!");
    final Schema schema = factory.newSchema(new StreamSource(is));
    final Validator v = schema.newValidator();
    v.validate(new StreamSource(new StringReader(xml)));
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) StringReader(java.io.StringReader) Event(org.opennms.netmgt.xml.event.Event) Validator(javax.xml.validation.Validator) Test(org.junit.Test)

Example 79 with SchemaFactory

use of javax.xml.validation.SchemaFactory in project wildfly by wildfly.

the class StandardConfigsXMLValidationUnitTestCase method parseXml.

private void parseXml(String xmlName) throws ParserConfigurationException, SAXException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(new ErrorHandlerImpl());
    schemaFactory.setResourceResolver(DEFAULT_RESOURCE_RESOLVER);
    Schema schema = schemaFactory.newSchema(SCHEMAS);
    Validator validator = schema.newValidator();
    validator.setErrorHandler(new ErrorHandlerImpl());
    validator.setFeature("http://apache.org/xml/features/validation/schema", true);
    validator.setResourceResolver(DEFAULT_RESOURCE_RESOLVER);
    validator.validate(new StreamSource(getXmlFile(xmlName)));
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) Validator(javax.xml.validation.Validator)

Example 80 with SchemaFactory

use of javax.xml.validation.SchemaFactory in project wildfly by wildfly.

the class XSDValidationUnitTestCase method validateXsd.

private void validateXsd(final File xsdFile) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.parse(xsdFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(new ErrorHandlerImpl());
    schemaFactory.setResourceResolver(new XMLResourceResolver());
    Schema schema = schemaFactory.newSchema(resource("schema/XMLSchema.xsd"));
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(document));
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) XMLResourceResolver(org.jboss.metadata.parser.util.XMLResourceResolver) Schema(javax.xml.validation.Schema) Document(org.w3c.dom.Document) Validator(javax.xml.validation.Validator)

Aggregations

SchemaFactory (javax.xml.validation.SchemaFactory)92 Schema (javax.xml.validation.Schema)72 StreamSource (javax.xml.transform.stream.StreamSource)47 Validator (javax.xml.validation.Validator)39 SAXException (org.xml.sax.SAXException)29 Source (javax.xml.transform.Source)28 IOException (java.io.IOException)20 URL (java.net.URL)18 DOMSource (javax.xml.transform.dom.DOMSource)18 JAXBContext (javax.xml.bind.JAXBContext)17 File (java.io.File)16 InputStream (java.io.InputStream)16 InputSource (org.xml.sax.InputSource)14 DocumentBuilder (javax.xml.parsers.DocumentBuilder)13 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)12 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)12 Unmarshaller (javax.xml.bind.Unmarshaller)11 Test (org.junit.Test)10 Document (org.w3c.dom.Document)10 ByteArrayInputStream (java.io.ByteArrayInputStream)8