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:org.docx4j.openpackaging.parts.JaxbXmlPart.java

public E unmarshal(org.w3c.dom.Element el) throws JAXBException {

    try {//from www.  ja  v a  2  s  .co  m

        Unmarshaller u = jc.createUnmarshaller();
        JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler();
        eventHandler.setContinue(false);
        u.setEventHandler(eventHandler);

        try {
            jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(el));
        } catch (UnmarshalException ue) {
            log.info("encountered unexpected content; pre-processing");
            try {
                org.w3c.dom.Document doc;
                if (el instanceof org.w3c.dom.Document) {
                    doc = (org.w3c.dom.Document) el;
                } else {
                    // Hope for the best. Dodgy though; what if this is
                    // being used on something deep in the tree?
                    // TODO: revisit
                    doc = el.getOwnerDocument();
                }
                eventHandler.setContinue(true);
                JAXBResult result = XmlUtils.prepareJAXBResult(jc);
                Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor();
                XmlUtils.transform(doc, mcPreprocessorXslt, null, result);
                jaxbElement = (E) XmlUtils.unwrap(result.getResult());
            } catch (Exception e) {
                throw new JAXBException("Preprocessing exception", e);
            }
        }
        return jaxbElement;

    } catch (JAXBException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:org.docx4j.XmlUtils.java

public static Object unmarshal(InputStream is, JAXBContext jc) throws JAXBException {

    // Guard against XXE
    XMLInputFactory xif = XMLInputFactory.newInstance();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception
    XMLStreamReader xsr = null;// ww  w .  j  ava 2s  . com
    try {
        xsr = xif.createXMLStreamReader(is);
    } catch (XMLStreamException e) {
        throw new JAXBException(e);
    }

    Object o = null;
    Unmarshaller u = jc.createUnmarshaller();

    JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler();
    //      if (is.markSupported()) {
    //         // Only fail hard if we know we can restart
    //         eventHandler.setContinue(false);
    //      }
    u.setEventHandler(eventHandler);
    try {
        o = u.unmarshal(xsr);
        return o;
    } catch (UnmarshalException ue) {

        if (ue.getLinkedException() != null && ue.getLinkedException().getMessage().contains("entity")) {

            /*
               Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,19]
               Message: The entity "xxe" was referenced, but not declared.
                  at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
                  at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(Unknown Source)
                */
            log.error(ue.getMessage(), ue);
            throw ue;
        }

        if (is.markSupported()) {
            // When reading from zip, we use a ByteArrayInputStream,
            // which does support this.

            log.info("encountered unexpected content; pre-processing");
            eventHandler.setContinue(true);

            try {
                Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor();
                is.reset();
                JAXBResult result = XmlUtils.prepareJAXBResult(jc);
                XmlUtils.transform(new StreamSource(is), mcPreprocessorXslt, null, result);
                return //XmlUtils.unwrap(
                result.getResult();
            } catch (Exception e) {
                throw new JAXBException("Preprocessing exception", e);
            }

        } else {
            log.error(ue.getMessage(), ue);
            log.error(".. and mark not supported");
            throw ue;
        }
    }

}

From source file:org.docx4j.XmlUtils.java

public static Object unmarshalString(String str, JAXBContext jc, Class declaredType) throws JAXBException {
    Unmarshaller u = jc.createUnmarshaller();
    u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());
    Object o = u.unmarshal(new javax.xml.transform.stream.StreamSource(new java.io.StringReader(str)),
            declaredType);//w  w  w  .  j a  v a  2  s .  c om
    if (o instanceof JAXBElement) {
        return ((JAXBElement) o).getValue();
    } else {
        return o;
    }
}

From source file:org.docx4j.XmlUtils.java

public static Object unmarshalString(String str, JAXBContext jc) throws JAXBException {
    log.debug("Unmarshalling '" + str + "'");
    Unmarshaller u = jc.createUnmarshaller();
    u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());
    return u.unmarshal(new javax.xml.transform.stream.StreamSource(new java.io.StringReader(str)));
}

From source file:org.docx4j.XmlUtils.java

public static Object unmarshal(Node n) throws JAXBException {

    Unmarshaller u = Context.jc.createUnmarshaller();
    u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());

    return u.unmarshal(n);
}

From source file:org.docx4j.XmlUtils.java

public static Object unmarshal(Node n, JAXBContext jc, Class declaredType) throws JAXBException {

    // THIS DOESN"T WORK PROPERLY WITH 1.6.0.03 JAXB RI
    // (at least with CTTextParagraphProperties in 
    //  a Xalan org.apache.xml.dtm.ref.DTMNodeProxy)
    // but converting the Node to a String and
    // unmarshalling that is fine!

    Unmarshaller u = jc.createUnmarshaller();
    u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());
    Object o = u.unmarshal(n, declaredType);
    if (o instanceof javax.xml.bind.JAXBElement) {
        return ((JAXBElement) o).getValue();
    } else {/*from   www. j ava 2  s  . co m*/
        return o;
    }
}

From source file:org.docx4j.XmlUtils.java

/**
 * Prepare a JAXB transformation result for some given context.
 * @param context The JAXB context./*from   www.  j  av a2  s .c  o  m*/
 * @return The result data structure created.
 * @throws Docx4JException In case of configuration errors.
 */
public static JAXBResult prepareJAXBResult(final JAXBContext context) throws Docx4JException {

    final JAXBResult result;
    try {
        final Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setEventHandler(new JaxbValidationEventHandler());
        result = new JAXBResult(unmarshaller);

    } catch (JAXBException e) {
        throw new Docx4JException("Error preparing empty JAXB result", e);
    }
    return result;
}

From source file:org.eclipse.smila.connectivity.framework.schema.internal.JaxbPluginContext.java

/**
 * Creates the validating unmarshaller./*w  w  w.java  2 s  .  c o  m*/
 * 
 * @return the unmarshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 * @throws SchemaNotFoundException
 *           the index order schema not found exception
 */
public Unmarshaller createValidatingUnmarshaller() throws JAXBException, SchemaNotFoundException {
    initilize();
    assertNotNull(_context);
    final Unmarshaller unmarshaller = _context.createUnmarshaller();
    final SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    try {
        sf.setResourceResolver(new XSDContextURIResolver(sf.getResourceResolver()));
        final javax.xml.validation.Schema schema = sf
                .newSchema(Platform.getBundle(_id).getEntry(_plugIn.getSchemaLocation()));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(final ValidationEvent ve) {
                if (ve.getSeverity() != ValidationEvent.WARNING) {
                    final ValidationEventLocator vel = ve.getLocator();
                    _log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                    return false;
                }
                return true;
            }
        });
    } catch (final org.xml.sax.SAXException se) {
        throw new SchemaRuntimeException("Unable to validate due to following error.", se);
    }
    return unmarshaller;
}

From source file:org.eclipse.smila.management.jmx.client.helpers.ConfigLoader.java

/**
 * Load./*from   w  w w. j  a v  a2 s. co  m*/
 * 
 * @param is
 *          the is
 * 
 * @return the cmd config type
 * 
 * @throws ConfigurationLoadException
 *           the configuration load exception
 */
public static JmxClientConfigType load(final InputStream is) throws ConfigurationLoadException {
    try {
        final JAXBContext context = JAXBContext.newInstance("org.eclipse.smila.management.jmx.client.config");
        final SchemaFactory schemaFactory = SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory.newSchema(new File("schemas/jmxclient.xsd"));
        final Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(createValidationEventHandler());
        Object result = unmarshaller.unmarshal(is);
        if (result != null) {
            if (result instanceof JAXBElement) {
                result = ((JAXBElement) result).getValue();
            }
        }
        return (JmxClientConfigType) result;
    } catch (final Throwable e) {
        throw new ConfigurationLoadException("Unable to load configuration", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (final Throwable e) {
                ;// nothing
            }
        }
    }
}

From source file:org.eclipse.smila.utils.jaxb.JaxbUtils.java

/**
 * Creates the validating unmarshaller./*  w  ww  .  j  a  va2s.  co m*/
 * 
 * @param context
 *          the context
 * @param schema
 *          the schema
 * 
 * @return the unmarshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 */
public static Unmarshaller createValidatingUnmarshaller(final JAXBContext context, final Schema schema)
        throws JAXBException {
    if (schema == null) {
        throw new IllegalArgumentException("Schema is not found!");
    }
    final Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(createValidationEventHandler());
    return unmarshaller;
}