Search in sources :

Example 76 with Schema

use of javax.xml.validation.Schema 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 Schema

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

the class JaxbUtils method getMarshallerFor.

public static Marshaller getMarshallerFor(final Object obj, final JAXBContext jaxbContext) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());
    Map<Class<?>, Marshaller> marshallers = m_marshallers.get();
    if (jaxbContext == null) {
        if (marshallers == null) {
            marshallers = new WeakHashMap<Class<?>, Marshaller>();
            m_marshallers.set(marshallers);
        }
        if (marshallers.containsKey(clazz)) {
            LOG.trace("found unmarshaller for {}", clazz);
            return marshallers.get(clazz);
        }
    }
    LOG.trace("creating unmarshaller for {}", clazz);
    try {
        final JAXBContext context;
        if (jaxbContext == null) {
            context = getContextFor(clazz);
        } else {
            context = jaxbContext;
        }
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        if (context.getClass().getName().startsWith("org.eclipse.persistence.jaxb")) {
            marshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER, new EmptyNamespacePrefixMapper());
            marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, true);
        }
        final Schema schema = getValidatorFor(clazz);
        marshaller.setSchema(schema);
        if (jaxbContext == null)
            marshallers.put(clazz, marshaller);
        return marshaller;
    } catch (final JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
    }
}
Also used : Marshaller(javax.xml.bind.Marshaller) XmlSchema(javax.xml.bind.annotation.XmlSchema) Schema(javax.xml.validation.Schema) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext)

Example 78 with Schema

use of javax.xml.validation.Schema 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 79 with Schema

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

the class JaxbUtils method getUnmarshallerFor.

/**
     * Get a JAXB unmarshaller for the given object.  If no JAXBContext is provided,
     * JAXBUtils will create and cache a context for the given object.
     * @param obj The object type to be unmarshalled.
     * @param jaxbContext An optional JAXB context to create the unmarshaller from.
     * @param validate TODO
     * @return an Unmarshaller
     */
public static Unmarshaller getUnmarshallerFor(final Object obj, final JAXBContext jaxbContext, boolean validate) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());
    Unmarshaller unmarshaller = null;
    Map<Class<?>, Unmarshaller> unmarshallers = m_unMarshallers.get();
    if (jaxbContext == null) {
        if (unmarshallers == null) {
            unmarshallers = new WeakHashMap<Class<?>, Unmarshaller>();
            m_unMarshallers.set(unmarshallers);
        }
        if (unmarshallers.containsKey(clazz)) {
            LOG.trace("found unmarshaller for {}", clazz);
            unmarshaller = unmarshallers.get(clazz);
        }
    }
    if (unmarshaller == null) {
        try {
            if (jaxbContext == null) {
                unmarshaller = getContextFor(clazz).createUnmarshaller();
            } else {
                unmarshaller = jaxbContext.createUnmarshaller();
            }
        } catch (final JAXBException e) {
            throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
        }
    }
    LOG.trace("created unmarshaller for {}", clazz);
    if (validate) {
        final Schema schema = getValidatorFor(clazz);
        if (schema == null) {
            LOG.trace("Validation is enabled, but no XSD found for class {}", clazz.getSimpleName());
        }
        unmarshaller.setSchema(schema);
    }
    if (jaxbContext == null)
        unmarshallers.put(clazz, unmarshaller);
    return unmarshaller;
}
Also used : JAXBException(javax.xml.bind.JAXBException) XmlSchema(javax.xml.bind.annotation.XmlSchema) Schema(javax.xml.validation.Schema) Unmarshaller(javax.xml.bind.Unmarshaller)

Example 80 with Schema

use of javax.xml.validation.Schema 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)

Aggregations

Schema (javax.xml.validation.Schema)102 SchemaFactory (javax.xml.validation.SchemaFactory)72 Validator (javax.xml.validation.Validator)51 StreamSource (javax.xml.transform.stream.StreamSource)45 SAXException (org.xml.sax.SAXException)35 Source (javax.xml.transform.Source)29 DOMSource (javax.xml.transform.dom.DOMSource)25 IOException (java.io.IOException)22 JAXBContext (javax.xml.bind.JAXBContext)18 Document (org.w3c.dom.Document)18 InputStream (java.io.InputStream)17 File (java.io.File)15 URL (java.net.URL)15 DocumentBuilder (javax.xml.parsers.DocumentBuilder)14 JAXBException (javax.xml.bind.JAXBException)13 Unmarshaller (javax.xml.bind.Unmarshaller)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13 InputSource (org.xml.sax.InputSource)13 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)12 SAXParseException (org.xml.sax.SAXParseException)9