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);
}
}
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);
}
}
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;
}
}
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;
}
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)));
}
Aggregations