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.codice.ddf.parser.xml.XmlParser.java

private <T> T unmarshal(ParserConfigurator configurator, Function<Unmarshaller, T> func)
        throws ParserException {
    JAXBContext jaxbContext = getContext(configurator.getContextPath(), configurator.getClassLoader());

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {/*ww  w  .  jav a 2  s  .  c o  m*/
        Thread.currentThread().setContextClassLoader(configurator.getClassLoader());

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        if (configurator.getAdapter() != null) {
            unmarshaller.setAdapter(configurator.getAdapter());
        }
        if (configurator.getHandler() != null) {
            unmarshaller.setEventHandler(configurator.getHandler());
        }
        for (Map.Entry<String, Object> propRow : configurator.getProperties().entrySet()) {
            unmarshaller.setProperty(propRow.getKey(), propRow.getValue());
        }

        return func.apply(unmarshaller);
    } catch (RuntimeException e) {
        LOGGER.error("Error unmarshalling ", e);
        throw new ParserException("Error unmarshalling", e);
    } catch (JAXBException e) {
        LOGGER.error("Error unmarshalling ", e);
        throw new ParserException("Error unmarshalling", e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
}

From source file:org.datacleaner.configuration.JaxbConfigurationReader.java

/**
 * Convenience method to get the untouched JAXB configuration object from an
 * inputstream.//from   www. ja v  a  2  s . c  o m
 * 
 * @param inputStream
 * @return
 */
public Configuration unmarshall(InputStream inputStream) {
    try {
        final Unmarshaller unmarshaller = _jaxbContext.createUnmarshaller();
        unmarshaller.setEventHandler(new JaxbValidationEventHandler());

        final Configuration configuration = (Configuration) unmarshaller.unmarshal(inputStream);
        return configuration;
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.datacleaner.job.JaxbJobReader.java

private JobType unmarshallJob(InputStream inputStream) {
    try {/*from  w w  w  . j  ava2  s. c  om*/
        Unmarshaller unmarshaller = _jaxbContext.createUnmarshaller();

        unmarshaller.setEventHandler(new JaxbValidationEventHandler());
        JobType job = (JobType) unmarshaller.unmarshal(inputStream);
        return job;
    } catch (JAXBException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.dkpro.core.io.xces.XcesBasicXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();//from  w  ww.j  av a  2  s  .c o  m
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReaderBasic = xmlInputFactory.createXMLEventReader(is);

        //JAXB context for XCES body with basic type
        JAXBContext contextBasic = JAXBContext.newInstance(XcesBodyBasic.class);
        Unmarshaller unmarshallerBasic = contextBasic.createUnmarshaller();

        unmarshallerBasic.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent eBasic = null;
        while ((eBasic = xmlEventReaderBasic.peek()) != null) {
            if (isStartElement(eBasic, "body")) {
                try {
                    XcesBodyBasic parasBasic = (XcesBodyBasic) unmarshallerBasic
                            .unmarshal(xmlEventReaderBasic, XcesBodyBasic.class).getValue();
                    readPara(jb, parasBasic);
                } catch (RuntimeException ex) {
                    getLogger().warn("Input is not in basic xces format.");
                }
            } else {
                xmlEventReaderBasic.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}

From source file:org.dkpro.core.io.xces.XcesXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();//w  w w  .j a  v a 2 s  .c  o m
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);

        JAXBContext context = JAXBContext.newInstance(XcesBody.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent e = null;
        while ((e = xmlEventReader.peek()) != null) {

            if (isStartElement(e, "body")) {
                try {
                    XcesBody paras = (XcesBody) unmarshaller.unmarshal(xmlEventReader, XcesBody.class)
                            .getValue();
                    readPara(jb, paras);
                } catch (RuntimeException ex) {
                    System.out.println("Unable to parse XCES format: " + ex);
                }
            } else {
                xmlEventReader.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}

From source file:org.docx4all.xml.ElementMLFactory.java

public final static DocumentML createDocumentML(FileObject f, boolean applyFilter) throws IOException {
    if (f == null || !(Constants.DOCX_STRING.equalsIgnoreCase(f.getName().getExtension())
            || Constants.FLAT_OPC_STRING.equalsIgnoreCase(f.getName().getExtension()))) {
        throw new IllegalArgumentException("Not a .docx (or .xml) file.");
    }/*from   www . ja v a2s  .  co  m*/

    DocumentML docML = null;
    try {
        WordprocessingMLPackage wordMLPackage;
        if (Constants.DOCX_STRING.equalsIgnoreCase(f.getName().getExtension())) {
            // .docx
            LoadFromVFSZipFile loader = new LoadFromVFSZipFile(true);
            //LoadFromVFSZipFile.setCustomXmlDataStorageClass(new org.docx4j.model.datastorage.Dom4jCustomXmlDataStorage());
            wordMLPackage = (WordprocessingMLPackage) loader.getPackageFromFileObject(f);
        } else {
            // .xml

            // First get the Flat OPC package from the File Object
            InputStream is = f.getContent().getInputStream();

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

            javax.xml.bind.JAXBElement j = (javax.xml.bind.JAXBElement) u.unmarshal(is);
            org.docx4j.xmlPackage.Package flatOpc = (org.docx4j.xmlPackage.Package) j.getValue();
            System.out.println("unmarshalled ");

            // Now convert it to a docx4j WordML Package            
            FlatOpcXmlImporter importer = new FlatOpcXmlImporter(flatOpc);
            wordMLPackage = (WordprocessingMLPackage) importer.get();
        }

        if (applyFilter) {
            wordMLPackage = XmlUtil.applyFilter(wordMLPackage);
        }
        docML = new DocumentML(wordMLPackage);
    } catch (Docx4JException exc) {
        throw new IOException(exc);
    } catch (Exception exc) {
        throw new IOException(exc);
    }

    return docML;
}

From source file:org.docx4j.fonts.BestMatchingMapper.java

/**
 * Get Microsoft fonts/*from   ww w .  j  av  a 2s  .co m*/
 * We need these:
 * 1. On Microsoft platform, to embed in PDF output
 * 2. docx4all - all platforms - to populate font dropdown list */
private final static void setupMicrosoftFontFilenames() throws Exception {

    java.lang.ClassLoader classLoader = BestMatchingMapper.class.getClassLoader();
    JAXBContext msFontsContext = JAXBContext.newInstance("org.docx4j.fonts.microsoft", classLoader);

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

    log.info("unmarshalling fonts.microsoft \n\n");
    // Get the xml file
    java.io.InputStream is = null;
    // Works in Eclipse - note absence of leading '/'
    is = org.docx4j.utils.ResourceUtils.getResource("org/docx4j/fonts/microsoft/MicrosoftFonts.xml");

    org.docx4j.fonts.microsoft.MicrosoftFonts msFonts = (org.docx4j.fonts.microsoft.MicrosoftFonts) u
            .unmarshal(is);

    List<MicrosoftFonts.Font> msFontsList = msFonts.getFont();

    for (MicrosoftFonts.Font font : msFontsList) {
        msFontsFilenames.put((font.getName()), font); // 20080318 - normalised
        //log.debug( "put msFontsFilenames: " + normalise(font.getName()) );
    }

}

From source file:org.docx4j.fonts.BestMatchingMapper.java

/**
 * Get candidate substitutions //  w w w .j  ava2  s.co m
 * On a non-MS platform, we need these for two things:
 * 1.  to embed this font in the PDF output, in place of MS font
 * 2.  in docx4all, use in editor 
 * but it will only be used if there is no panose match.
 * 
 * Issues with  FontSubstitutions.xml, as noted and addressed by Jeromy Evans
 * http://www.docx4java.org/forums/docx-java-f6/bestmatchingmapper-bugs-handling-explicit-substitutions-t940.html
 *  
 * (1) FontSubstutitions.xml uses the lowercase whitespace and punctuation removed name of the font. If the document contains "Times New Roman" it is not matched to the equivalent replace element for "timesnewroman". Similarly "Arial" is not matched to "arial".
 * (2) When matched, the method searching PhysicalFonts for the substitution font also uses the short key, not the proper name used by PhysicalFonts. For example, if matching "arial" to a substitute it tries to find "freesans" in PhysicalFont's map instead of "Free Sans".
 * (3) On the system tested, the SubsFonts value is inclusive of the leading whitespace (eg. in the line above, the first token is "\n\t\tarial' instead of "arial" (seems odd that whitespace is included after unmarshalling). This means the first substitution always fails to match a font. As, by convention, the first token is usually the name of the font, this effectively means on systems where msttcorefonts are installed, the BestMatchingMapper fails to match the exact font. ie. it can't match "arial" to "arial" because the substitution is named "\n\t\tarial".
 * 
 *  */
private final static void setupExplicitSubstitutionsMap() throws Exception {

    java.lang.ClassLoader classLoader = BestMatchingMapper.class.getClassLoader();
    JAXBContext substitutionsContext = JAXBContext.newInstance("org.docx4j.fonts.substitutions", classLoader);

    Unmarshaller u2 = substitutionsContext.createUnmarshaller();
    u2.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());

    log.info("unmarshalling fonts.substitutions");
    // Get the xml file
    java.io.InputStream is2 = null;
    // Works in Eclipse - note absence of leading '/'
    is2 = org.docx4j.utils.ResourceUtils.getResource("org/docx4j/fonts/substitutions/FontSubstitutions.xml");

    org.docx4j.fonts.substitutions.FontSubstitutions fs = (org.docx4j.fonts.substitutions.FontSubstitutions) u2
            .unmarshal(is2);

    List<FontSubstitutions.Replace> replaceList = fs.getReplace();

    for (FontSubstitutions.Replace replacement : replaceList) {
        explicitSubstitutionsMap.put(replacement.getName(), replacement);
    }

}

From source file:org.docx4j.model.datastorage.OpenDoPEIntegrity.java

private void process(JaxbXmlPart part) throws Docx4JException {

    org.docx4j.openpackaging.packages.OpcPackage pkg = part.getPackage();
    // Binding is a concept which applies more broadly
    // than just Word documents.

    org.w3c.dom.Document doc = XmlUtils.marshaltoW3CDomDocument(part.getJaxbElement());

    JAXBContext jc = Context.jc;
    try {//from   ww w.ja v  a  2  s  . com
        // Use constructor which takes Unmarshaller, rather than JAXBContext,
        // so we can set JaxbValidationEventHandler
        Unmarshaller u = jc.createUnmarshaller();
        u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());
        javax.xml.bind.util.JAXBResult result = new javax.xml.bind.util.JAXBResult(u);

        Map<String, Object> transformParameters = new HashMap<String, Object>();
        transformParameters.put("OpenDoPEIntegrity", this);

        org.docx4j.XmlUtils.transform(doc, xslt, transformParameters, result);

        part.setJaxbElement(result);
    } catch (Exception e) {
        throw new Docx4JException("Problems ensuring integrity", e);
    }

}

From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java

/**
* Unmarshal XML data from the specified InputStream and return the
* resulting content tree. Validation event location information may be
* incomplete when using this form of the unmarshal API.
* 
* <p>/*  w w  w.j ava  2  s  .c  o m*/
* Implements <a href="#unmarshalGlobal">Unmarshal Global Root Element</a>.
* 
* @param is
*            the InputStream to unmarshal XML data from
* @return the newly created root object of the java content tree
* 
* @throws JAXBException
*             If any unexpected errors occur while unmarshalling
*/
public E unmarshal(java.io.InputStream is) throws JAXBException {

    try {
        /* To avoid possible XML External Entity Injection attack,
         * we need to configure the processor.
         * 
         * We use STAX XMLInputFactory to do that.
         * 
         * createXMLStreamReader(is) is 40% slower than unmarshal(is).
         * 
         * But it seems to be the best we can do ... 
         * 
         *   org.w3c.dom.Document doc = XmlUtils.getNewDocumentBuilder().parse(is)
         *   unmarshal(doc)
         * 
         * ie DOM is 5x slower than unmarshal(is)
         * 
         */

        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 = xif.createXMLStreamReader(is);

        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 {
            jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(xsr));
        } 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);
                    jaxbElement = (E) 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;
            }
        }

    } catch (XMLStreamException e1) {
        log.error(e1.getMessage(), e1);
        throw new JAXBException(e1);
    }

    return jaxbElement;

}