Example usage for javax.xml.bind Unmarshaller setEventHandler

List of usage examples for javax.xml.bind Unmarshaller setEventHandler

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller setEventHandler.

Prototype

public void setEventHandler(ValidationEventHandler handler) throws JAXBException;

Source Link

Document

Allow an application to register a ValidationEventHandler .

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Foo.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    StringReader xml = new StringReader("<foo><bar>toast</bar></foo>");
    Foo foo = (Foo) unmarshaller.unmarshal(xml);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override//from   w w w.ja v  a2s  .co  m
        public boolean handleEvent(ValidationEvent ve) {
            System.out.println(ve.getMessage());
            return true;
        }
    });

    System.out.println(foo.isBar());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    // Unmarshal #1 = Default Unmarshal
    System.out.println("Unmarshal #1");
    Root root = (Root) unmarshaller.unmarshal(new StringReader(XML));
    marshaller.marshal(root, System.out);

    // Unmarshal #2 - Override Default ValidationEventHandler
    System.out.println("Unmarshal #2");
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override//from w  w  w  .  ja  v  a2s .  c  o  m
        public boolean handleEvent(ValidationEvent event) {
            System.out.println(event.getMessage());
            return false;
        }
    });
    unmarshaller.unmarshal(new StringReader(XML));
}

From source file:Main.java

public static <T> T deserialize(Class<T> res, InputStream is) throws JAXBException {
    Unmarshaller u = CTX.createUnmarshaller();
    u.setEventHandler(new DefaultValidationEventHandler());
    return res.cast(u.unmarshal(is));
}

From source file:Main.java

public static <T> T deserialize(Class<T> res, InputStream is) throws JAXBException {
    String pkg = res.getPackage().getName();
    JAXBContext jc = getCachedContext(pkg);
    Unmarshaller u = jc.createUnmarshaller();
    u.setEventHandler(new DefaultValidationEventHandler());
    return res.cast(u.unmarshal(is));
}

From source file:Main.java

/**
 * Unmarshal./*from  ww  w  . j  a  va2s  .com*/
 *
 * @param inputSource the input source
 * @param clazz the clazz
 * @return the object
 * @throws JAXBException the jAXB exception
 */
public static Object unmarshal(InputSource inputSource, Class<?> clazz) throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(clazz);
    Unmarshaller u = jc.createUnmarshaller();
    ValidationEventCollector vec = new ValidationEventCollector();
    u.setEventHandler(vec);
    Object o1 = u.unmarshal(inputSource);
    return o1;

}

From source file:de.bloxel.engine.util.JAXBUtils.java

public static <T> T unmarschal(final InputStream inputStream, final Class<T> aClass) {
    try {//from   ww  w.  j a v  a2s.  c o m
        // http://jaxb.java.net/faq/index.html#classloader
        final JAXBContext jc = JAXBContext.newInstance(getPackageCanonicalName(aClass));
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        // http://jaxb.java.net/guide/Unmarshalling_is_not_working__Help_.html
        unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
        final XMLInputFactory staxFactory = XMLInputFactory.newInstance();
        final XMLStreamReader xmlReader = staxFactory.createXMLStreamReader(inputStream);
        return unmarshaller.unmarshal(xmlReader, aClass).getValue();
    } catch (final JAXBException e) {
        throw new RuntimeException(String.format("Can't load unmarschal '%s'", aClass), e);
    } catch (final XMLStreamException e) {
        throw new RuntimeException(String.format("Can't load unmarschal '%s'", aClass), e);
    }
}

From source file:Main.java

public static <T> T unmarshal(Reader r, Class<T> clazz)
        throws JAXBException, XMLStreamException, FactoryConfigurationError {
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);//from  w  w  w .j  a  va  2  s.  co  m
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    XMLStreamReader xmlsr = XMLInputFactory.newFactory().createXMLStreamReader(r);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null);
    unmarshaller.setEventHandler(valEventHndlr);

    JAXBElement<T> elem = null;
    try {
        elem = unmarshaller.unmarshal(xmlsr, clazz);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new UnmarshalException(e.getMessage(), e);
        }
    }

    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Unmarshall Exception if there is a parsing error
                String msg = MessageFormat.format("Line {0}, Col: {1}: {2}",
                        valEvent.getLocator().getLineNumber(), valEvent.getLocator().getColumnNumber(),
                        valEvent.getLinkedException().getMessage());
                throw new UnmarshalException(msg, valEvent.getLinkedException());
            }
        }
    }
    return elem.getValue();
}

From source file:com.netflix.subtitles.ttml.TtmlParagraphResolver.java

private static <T> T deepCopy(T object, Class<T> clazz, String packages) {
    try {/*from w  ww  . j  a v a  2 s  .  com*/
        JAXBContext jaxbContext = JAXBContext.newInstance(packages);

        //  create marshaller which disable validation step
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setEventHandler(event -> true);

        //  create unmarshaller which disable validation step
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setEventHandler(event -> true);

        JAXBElement<T> contentObject = new JAXBElement<>(new QName(clazz.getName()), clazz, object);
        return unmarshaller.unmarshal(new JAXBSource(marshaller, contentObject), clazz).getValue();
    } catch (JAXBException e) {
        throw new ParseException("Time overlaps in <p> cannot be resolved.", e);
    }
}

From source file:ee.ria.xroad.opmonitordaemon.QueryRequestHandler.java

private static Unmarshaller createUnmarshaller(Class<?> clazz) throws Exception {
    Unmarshaller unmarshaller = JaxbUtils.createUnmarshaller(clazz);
    unmarshaller.setEventHandler(QueryRequestHandler::validationFailed);
    unmarshaller.setSchema(OP_MONITORING_SCHEMA);

    return unmarshaller;
}

From source file:ee.ria.xroad.common.message.SoapParserImpl.java

@SuppressWarnings("unchecked")
static <T> T unmarshalHeader(Class<?> clazz, SOAPHeader soapHeader, boolean checkRequiredFields)
        throws Exception {
    Unmarshaller unmarshaller = JaxbUtils.createUnmarshaller(clazz);

    if (checkRequiredFields) {
        unmarshaller.setListener(new RequiredHeaderFieldsChecker(clazz));
    }/*from ww  w.j av a 2 s .c o m*/

    unmarshaller.setEventHandler(event -> {
        switch (event.getSeverity()) {
        case ValidationEvent.WARNING:
            return true;
        case ValidationEvent.ERROR:
            Throwable t = event.getLinkedException();

            return !(t instanceof AccessorException && t.getCause() instanceof CodedException);
        case ValidationEvent.FATAL_ERROR:
            return false;
        default:
            return true;
        }
    });

    JAXBElement<T> jaxbElement = (JAXBElement<T>) unmarshaller.unmarshal(soapHeader, clazz);
    return jaxbElement.getValue();
}