Search in sources :

Example 21 with ValidationEvent

use of javax.xml.bind.ValidationEvent 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 22 with ValidationEvent

use of javax.xml.bind.ValidationEvent in project camel by apache.

the class JaxbDataFormat method createMarshaller.

protected Marshaller createMarshaller() throws JAXBException, SAXException, FileNotFoundException, MalformedURLException {
    Marshaller marshaller = getContext().createMarshaller();
    if (schema != null) {
        marshaller.setSchema(cachedSchema);
        marshaller.setEventHandler(new ValidationEventHandler() {

            public boolean handleEvent(ValidationEvent event) {
                // stop marshalling if the event is an ERROR or FATAL ERROR
                return event.getSeverity() == ValidationEvent.WARNING;
            }
        });
    }
    return marshaller;
}
Also used : Marshaller(javax.xml.bind.Marshaller) ValidationEventHandler(javax.xml.bind.ValidationEventHandler) ValidationEvent(javax.xml.bind.ValidationEvent)

Example 23 with ValidationEvent

use of javax.xml.bind.ValidationEvent in project ddf by codice.

the class TestXmlParserConfigurator method setup.

@Before
public void setup() {
    pc = new XmlParserConfigurator();
    testHandler = new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            return false;
        }
    };
    testAdapter = new XmlAdapter() {

        @Override
        public Object unmarshal(Object v) throws Exception {
            return null;
        }

        @Override
        public Object marshal(Object v) throws Exception {
            return null;
        }
    };
}
Also used : ValidationEventHandler(javax.xml.bind.ValidationEventHandler) ValidationEvent(javax.xml.bind.ValidationEvent) XmlAdapter(javax.xml.bind.annotation.adapters.XmlAdapter) Before(org.junit.Before)

Example 24 with ValidationEvent

use of javax.xml.bind.ValidationEvent in project cxf by apache.

the class DataWriterImpl method createMarshaller.

public Marshaller createMarshaller(Object elValue, MessagePartInfo part) {
    Class<?> cls = null;
    if (part != null) {
        cls = part.getTypeClass();
    }
    if (cls == null) {
        cls = null != elValue ? elValue.getClass() : null;
    }
    if (cls != null && cls.isArray() && elValue instanceof Collection) {
        Collection<?> col = (Collection<?>) elValue;
        elValue = col.toArray((Object[]) Array.newInstance(cls.getComponentType(), col.size()));
    }
    Marshaller marshaller;
    try {
        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
        marshaller.setListener(databinding.getMarshallerListener());
        databinding.applyEscapeHandler(!noEscape, eh -> JAXBUtils.setEscapeHandler(marshaller, eh));
        if (setEventHandler) {
            ValidationEventHandler h = veventHandler;
            if (veventHandler == null) {
                h = new ValidationEventHandler() {

                    public boolean handleEvent(ValidationEvent event) {
                        // continue on warnings only
                        return event.getSeverity() == ValidationEvent.WARNING;
                    }
                };
            }
            marshaller.setEventHandler(h);
        }
        final Map<String, String> nspref = databinding.getDeclaredNamespaceMappings();
        final Map<String, String> nsctxt = databinding.getContextualNamespaceMap();
        // set the prefix mapper if either of the prefix map is configured
        if (nspref != null || nsctxt != null) {
            Object mapper = JAXBUtils.setNamespaceMapper(nspref != null ? nspref : nsctxt, marshaller);
            if (nsctxt != null) {
                setContextualNamespaceDecls(mapper, nsctxt);
            }
        }
        if (databinding.getMarshallerProperties() != null) {
            for (Map.Entry<String, Object> propEntry : databinding.getMarshallerProperties().entrySet()) {
                try {
                    marshaller.setProperty(propEntry.getKey(), propEntry.getValue());
                } catch (PropertyException pe) {
                    LOG.log(Level.INFO, "PropertyException setting Marshaller properties", pe);
                }
            }
        }
        marshaller.setSchema(schema);
        AttachmentMarshaller atmarsh = getAttachmentMarshaller();
        marshaller.setAttachmentMarshaller(atmarsh);
        if (schema != null && atmarsh instanceof JAXBAttachmentMarshaller) {
            // we need a special even handler for XOP attachments
            marshaller.setEventHandler(new MtomValidationHandler(marshaller.getEventHandler(), (JAXBAttachmentMarshaller) atmarsh));
        }
    } catch (JAXBException ex) {
        if (ex instanceof javax.xml.bind.MarshalException) {
            javax.xml.bind.MarshalException marshalEx = (javax.xml.bind.MarshalException) ex;
            Message faultMessage = new Message("MARSHAL_ERROR", LOG, marshalEx.getLinkedException().getMessage());
            throw new Fault(faultMessage, ex);
        }
        throw new Fault(new Message("MARSHAL_ERROR", LOG, ex.getMessage()), ex);
    }
    for (XmlAdapter<?, ?> adapter : databinding.getConfiguredXmlAdapters()) {
        marshaller.setAdapter(adapter);
    }
    return marshaller;
}
Also used : AttachmentMarshaller(javax.xml.bind.attachment.AttachmentMarshaller) JAXBAttachmentMarshaller(org.apache.cxf.jaxb.attachment.JAXBAttachmentMarshaller) Marshaller(javax.xml.bind.Marshaller) AttachmentMarshaller(javax.xml.bind.attachment.AttachmentMarshaller) JAXBAttachmentMarshaller(org.apache.cxf.jaxb.attachment.JAXBAttachmentMarshaller) ValidationEventHandler(javax.xml.bind.ValidationEventHandler) MarshalException(javax.xml.bind.MarshalException) Message(org.apache.cxf.common.i18n.Message) PropertyException(javax.xml.bind.PropertyException) JAXBException(javax.xml.bind.JAXBException) Fault(org.apache.cxf.interceptor.Fault) JAXBAttachmentMarshaller(org.apache.cxf.jaxb.attachment.JAXBAttachmentMarshaller) MarshalException(javax.xml.bind.MarshalException) ValidationEvent(javax.xml.bind.ValidationEvent) Collection(java.util.Collection) Map(java.util.Map)

Example 25 with ValidationEvent

use of javax.xml.bind.ValidationEvent in project tomee by apache.

the class JaxbJavaee method unmarshal.

/**
 * Read in a T from the input stream.
 *
 * @param type     Class of object to be read in
 * @param in       input stream to read
 * @param validate whether to validate the input.
 * @param <T>      class of object to be returned
 * @return a T read from the input stream
 * @throws ParserConfigurationException is the SAX parser can not be configured
 * @throws SAXException                 if there is an xml problem
 * @throws JAXBException                if the xml cannot be marshalled into a T.
 */
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean validate) throws ParserConfigurationException, SAXException, JAXBException {
    final InputSource inputSource = new InputSource(in);
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(validate);
    final SAXParser parser = factory.newSAXParser();
    final JAXBContext ctx = JaxbJavaee.getContext(type);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {

        public boolean handleEvent(final ValidationEvent validationEvent) {
            System.out.println(validationEvent);
            return false;
        }
    });
    final JaxbJavaee.NoSourceFilter xmlFilter = new JaxbJavaee.NoSourceFilter(parser.getXMLReader());
    xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
    final SAXSource source = new SAXSource(xmlFilter, inputSource);
    currentPublicId.set(new TreeSet<String>());
    try {
        return unmarshaller.unmarshal(source);
    } finally {
        currentPublicId.set(null);
    }
}
Also used : InputSource(org.xml.sax.InputSource) ValidationEventHandler(javax.xml.bind.ValidationEventHandler) JAXBContext(javax.xml.bind.JAXBContext) SAXSource(javax.xml.transform.sax.SAXSource) ValidationEvent(javax.xml.bind.ValidationEvent) SAXParser(javax.xml.parsers.SAXParser) Unmarshaller(javax.xml.bind.Unmarshaller) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

ValidationEvent (javax.xml.bind.ValidationEvent)31 ValidationEventHandler (javax.xml.bind.ValidationEventHandler)18 Unmarshaller (javax.xml.bind.Unmarshaller)13 JAXBContext (javax.xml.bind.JAXBContext)12 InputSource (org.xml.sax.InputSource)11 SAXSource (javax.xml.transform.sax.SAXSource)10 SAXParser (javax.xml.parsers.SAXParser)9 SAXParserFactory (javax.xml.parsers.SAXParserFactory)9 SAXException (org.xml.sax.SAXException)6 ValidationEventLocatorExImpl (com.sun.xml.bind.util.ValidationEventLocatorExImpl)5 Marshaller (javax.xml.bind.Marshaller)5 PrintConversionEventImpl (javax.xml.bind.helpers.PrintConversionEventImpl)5 ValidationEventImpl (javax.xml.bind.helpers.ValidationEventImpl)5 ValidationEventLocatorImpl (javax.xml.bind.helpers.ValidationEventLocatorImpl)5 JAXBException (javax.xml.bind.JAXBException)3 SchemaFactory (javax.xml.validation.SchemaFactory)3 StringWriter (java.io.StringWriter)2 Writer (java.io.Writer)2 PropertyException (javax.xml.bind.PropertyException)2 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)2