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:com.aurel.track.exchange.docx.exporter.NumberingUtil.java

static void setNumbering(WordprocessingMLPackage newPkg) {
    java.io.InputStream is = null;
    try {//from   w w  w .j av a  2  s.  com
        is = ResourceUtils.getResource("com/aurel/track/exchange/docx/exporter/numbering.xml");
    } catch (IOException e) {
        LOGGER.error("Getting the KnownStyles.xml failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    JAXBContext jc = Context.jc;
    Unmarshaller unmarshaller = null;
    try {
        unmarshaller = jc.createUnmarshaller();
    } catch (JAXBException e) {
        LOGGER.error("Creating a JAXB unmarshaller failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        unmarshaller.setEventHandler(new JaxbValidationEventHandler());
    } catch (JAXBException e) {
        LOGGER.error("Setting the event handler for JAXB unmarshaller failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    Numbering numbering = null;
    try {
        numbering = (Numbering) unmarshaller.unmarshal(is);
    } catch (JAXBException e) {
        LOGGER.error("Unmarshalling the numbering.xml failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    NumberingDefinitionsPart numberingDefinitionsPart = null;
    try {
        numberingDefinitionsPart = new NumberingDefinitionsPart();
    } catch (InvalidFormatException e) {
        LOGGER.error("Creating the styles definition part failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    numberingDefinitionsPart.setPackage(newPkg);
    numberingDefinitionsPart.setJaxbElement(numbering);
    try {
        newPkg.getMainDocumentPart().addTargetPart(numberingDefinitionsPart);
    } catch (InvalidFormatException e) {
        LOGGER.error("Adding the target part to MainDocumentPart failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.rapid.server.RapidHttpServlet.java

public static Unmarshaller getUnmarshaller() throws JAXBException, IOException {

    // initialise the unmarshaller
    Unmarshaller unmarshaller = _jaxbContext.createUnmarshaller();
    // add the encrypted xml adapter
    unmarshaller.setAdapter(_encryptedXmlAdapter);

    // add a validation listener (this makes for better error messages)
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override/*from  w  w w  .j  a  va  2 s .co  m*/
        public boolean handleEvent(ValidationEvent event) {

            // get the location
            ValidationEventLocator location = event.getLocator();

            // log
            _logger.debug("JAXB validation event - " + event.getMessage()
                    + (location == null ? ""
                            : " at line " + location.getLineNumber() + ", column " + location.getColumnNumber()
                                    + ", node " + location.getNode()));

            // messages with "unrecognized type name" are very useful they're not sever themselves must almost always followed by a severe with a less meaningful message 
            if (event.getMessage().contains("unrecognized type name")
                    || event.getSeverity() == ValidationEvent.FATAL_ERROR) {
                return false;
            } else {
                return true;
            }

        }
    });

    // return
    return unmarshaller;
}

From source file:main.java.refinement_class.Useful.java

public static boolean validation(String schema_file, String xml_file) {
    Object obj = null;//  www .  ja  v  a2  s.  co m

    // create a JAXBContext capable of handling classes generated into
    // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class );

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance();

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

        try {

            javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file));

            u.setSchema((javax.xml.validation.Schema) schema);
            u.setEventHandler(new ValidationEventHandler() {
                // allow unmarshalling to continue even if there are errors
                public boolean handleEvent(ValidationEvent ve) {
                    // ignore warnings
                    if (ve.getSeverity() != ValidationEvent.WARNING) {
                        ValidationEventLocator vel = ve.getLocator();
                        System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber()
                                + "]:" + ve.getMessage());
                    }
                    return true;
                }
            });
        } catch (org.xml.sax.SAXException se) {
            System.out.println("Unable to validate due to following error.");
            se.printStackTrace();
            LOG.error(se.toString());
        }

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        LOG.error(e.toString());
    }

    return true;

}

From source file:main.java.refinement_class.Useful.java

public static Object unmashal2(String schema_file, String xml_file, Class c) {
    Object obj = null;/*from  w  w w . ja  v a  2  s.c o m*/
    try {

        // create a JAXBContext capable of handling classes generated into
        // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class );

        JAXBContext jc = JAXBContext.newInstance(c);

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

        try {

            javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file));

            u.setSchema((javax.xml.validation.Schema) schema);
            u.setEventHandler(new ValidationEventHandler() {
                // allow unmarshalling to continue even if there are errors
                public boolean handleEvent(ValidationEvent ve) {
                    // ignore warnings
                    if (ve.getSeverity() != ValidationEvent.WARNING) {
                        ValidationEventLocator vel = ve.getLocator();
                        System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber()
                                + "]:" + ve.getMessage());
                    }
                    return true;
                }
            });
        } catch (org.xml.sax.SAXException se) {
            System.out.println("Unable to validate due to following error.");
            se.printStackTrace();
            LOG.error(se.toString());
        }

        obj = u.unmarshal(new File(xml_file));

        // even though document was determined to be invalid unmarshalling,
        // marshal out result.
        //           System.out.println("");
        //         System.out.println("Still able to marshal invalid document");
        //       javax.xml.bind.Marshaller m = jc.createMarshaller();
        // m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
        //     m.marshal(poe, System.out);
    } catch (UnmarshalException ue) {
        // The JAXB specification does not mandate how the JAXB provider
        // must behave when attempting to unmarshal invalid XML data.
        // those cases, the JAXB provider is allowed to terminate the
        // call to unmarshal with an UnmarshalException.
        System.out.println("Caught UnmarshalException");
    } catch (JAXBException je) {
        je.printStackTrace();
        LOG.error(je.toString());
    }

    return obj;
}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

public static <T> T unmarshal(final Class<T> clazz, final InputSource inputSource,
        final JAXBContext jaxbContext, final boolean validate) {
    final Unmarshaller um = getUnmarshallerFor(clazz, jaxbContext, validate);

    LogUtils.tracef(clazz, "unmarshalling class %s from input source %s with unmarshaller %s",
            clazz.getSimpleName(), inputSource, um);
    try {/*www .  j a  va 2s.  c o m*/
        final XMLFilter filter = getXMLFilterForClass(clazz);
        final SAXSource source = new SAXSource(filter, inputSource);

        um.setEventHandler(new LoggingValidationEventHandler(clazz));

        final JAXBElement<T> element = um.unmarshal(source, clazz);
        return element.getValue();
    } catch (final SAXException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating an XML reader object", e);
    } catch (final JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("unmarshalling an object (" + clazz.getSimpleName() + ")", e);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

private static Object validate(final Unmarshaller unmarshaller,
        final ValidationEventHandler validationEventHandler, final Reader reader,
        final boolean includeMetaDataSchema) throws JAXBException, SAXException, IOException {

    Object jaxbObject = null;/*from  w  w w  .jav  a2s.co m*/
    try {
        // Set the schema for the unmarshaller
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory
                .newSchema(getSchemaSources(includeMetaDataSchema).toArray(new Source[] {}));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(validationEventHandler);

        // Unmarshal and validate
        jaxbObject = unmarshaller.unmarshal(reader);
    } catch (UnmarshalException ue) {
        // Swallow the exception. The ValidationEventHandler attached to the unmarshaller will
        // contain the validation events
        logger.info(ue);
    }

    return jaxbObject;
}

From source file:com.savoirtech.jaxb.engine.UnmarshallerPool.java

@Override
public Object makeObject() throws Exception {
    LOG.debug("Creating a new marshaller");
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationChecker());
    return unmarshaller;
}

From source file:com.mijao.poc.jaxb.UnmarshallerPool.java

@Override
public Object makeObject() throws Exception {
    logger.debug("Creating a new marshaller");
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationChecker());
    return unmarshaller;
}

From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParser.java

private Plist unmarshallPlist(InputSource project)
        throws SAXException, ParserConfigurationException, JAXBException {
    InputSource dtd = new InputSource(this.getClass().getResourceAsStream("/PropertyList-1.0.dtd"));
    SAXSource ss = createSAXSource(project, dtd);
    JAXBContext ctx = JAXBContext.newInstance(com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlist.class);
    Unmarshaller unmarshaller = ctx.createUnmarshaller();

    // unexpected elements should cause an error
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override//w w  w  .  j a v  a  2  s. c o m
        public boolean handleEvent(ValidationEvent event) {
            return false;
        }
    });

    return (Plist) unmarshaller.unmarshal(ss);
}

From source file:org.openwms.core.configuration.file.ApplicationPreferenceTest.java

/**
 * Just test to validate the given XML file against the schema declaration. If the XML file is not compliant with the schema, the test
 * will fail.//ww w  .java  2s .c o  m
 *
 * @throws Exception any error
 */
@Test
public void testReadPreferences() throws Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(ResourceUtils.getFile("classpath:preferences.xsd"));
    // Schema schema = schemaFactory.newSchema(new
    // URL("http://www.openwms.org/schema/preferences.xsd"));
    JAXBContext ctx = JAXBContext.newInstance("org.openwms.core.configuration.file");
    Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override
        public boolean handleEvent(ValidationEvent event) {
            RuntimeException ex = new RuntimeException(event.getMessage(), event.getLinkedException());
            LOGGER.error(ex.getMessage());
            throw ex;
        }
    });

    Preferences prefs = Preferences.class.cast(unmarshaller
            .unmarshal(ResourceUtils.getFile("classpath:org/openwms/core/configuration/file/preferences.xml")));
    for (AbstractPreference pref : prefs.getApplications()) {
        LOGGER.info(pref.toString());
    }
    for (AbstractPreference pref : prefs.getModules()) {
        LOGGER.info(pref.toString());
    }
    for (AbstractPreference pref : prefs.getUsers()) {
        LOGGER.info(pref.toString());
    }
}