Example usage for javax.xml.bind ValidationEventHandler ValidationEventHandler

List of usage examples for javax.xml.bind ValidationEventHandler ValidationEventHandler

Introduction

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

Prototype

ValidationEventHandler

Source Link

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   www.j av  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 ww. j a  v  a 2  s  .  com*/
        public boolean handleEvent(ValidationEvent event) {
            System.out.println(event.getMessage());
            return false;
        }
    });
    unmarshaller.unmarshal(new StringReader(XML));
}

From source file:MarshalValidation.java

public static void main(String[] args) throws Exception {
    Person p = new Person();
    p.setFirstName("B");
    p.setLastName("H");

    JAXBContext context = JAXBContext.newInstance(Person.class);
    Marshaller marshaller = context.createMarshaller();

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("person.xsd"));

    marshaller.setSchema(schema);//  w  w  w . jav  a 2  s  .co m
    marshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent event) {
            System.out.println(event);
            return false;
        }
    });

    marshaller.marshal(p, System.out);
}

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//  w w  w .j av a2 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: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  av  a  2 s. co  m*/
        public boolean handleEvent(ValidationEvent event) {
            return false;
        }
    });

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

From source file:it.cnr.icar.eric.common.cms.AbstractService.java

protected Unmarshaller getUnmarshaller() throws JAXBException {
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    //unmarshaller.setValidating(true);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent event) {
            boolean keepOn = false;

            return keepOn;
        }//from  www .jav a2s .c  om
    });

    return unmarshaller;
}

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

public static Object unmashal(String schema_file, String xml_file, Class c) {
    Object obj = null;/*from  w  w w.j av  a2s  .c om*/
    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 {

            //                LOG.info("\n\n  XX -->> Schema file: " + schema_file);
            //                LOG.info("\n\n  XX -->> xml_file file: " + xml_file);
            //++
            javax.xml.validation.Schema schema;
            if (schema_file.contains("/tmp/")) {
                schema = sf.newSchema(new File(schema_file));
            } else {
                URL urlSchema = getUrl(H2mserviceImpl.class, schema_file);
                //                    LOG.info("\n\n  XX -->> urlSchema: " + urlSchema.getPath());
                schema = sf.newSchema(urlSchema);
            }
            //--
            //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("===>[1]ERROR Unmashaling \n\n" + se.toString());
            LOG.error(Useful.getStackTrace(se));
        } catch (Exception e) {
            LOG.error("===>[2]ERROR Unmashaling \n\n" + e.toString());
            LOG.error(Useful.getStackTrace(e));
        }

        if (xml_file.contains("/tmp/")) {
            obj = u.unmarshal(new File(xml_file));
        } else {
            URL url_xml_file = getUrl(H2mserviceImpl.class, xml_file);
            LOG.info("\n\n  XX -->> url_xml_file: " + url_xml_file.getPath());
            obj = u.unmarshal(url_xml_file);
        }

        //--
        //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");
        LOG.error("===>[3]ERROR Unmashaling \n\n" + ue.toString());
    } catch (JAXBException je) {
        je.printStackTrace();
        LOG.error("===>[4]ERROR Unmashaling \n\n" + je.toString());
        LOG.error(Useful.getStackTrace(je));
    } catch (Exception e) {
        LOG.error("===>[5]ERROR Unmashaling \n\n" + e.toString());
        LOG.error(Useful.getStackTrace(e));
    }

    if (obj == null) {
        LOG.error("===>[6]ERROR Unmashaling Object NULL");
    }
    return obj;
}

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./*  w ww .  j a v a2  s  .  com*/
 *
 * @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());
    }
}

From source file:org.cleverbus.core.common.asynch.TraceHeaderProcessor.java

private ValidationEventHandler getValidationEventHandler() {
    return new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent event) {
            if (event.getSeverity() == ValidationEvent.WARNING) {
                Log.warn("Ignored {}", event, event.getLinkedException());
                return true; // handled - ignore as WARNING does not prevent unmarshalling
            } else {
                return false; // not handled - ERROR and FATAL_ERROR prevent successful unmarshalling
            }/*from   ww  w.j av  a 2s. c  o m*/
        }
    };
}

From source file:com.bitplan.jaxb.JaxbFactory.java

/**
 * get a fitting Unmarshaller//w w w.  ja v a  2 s .  co m
 * 
 * @return - the Unmarshaller for the classOfT set
 * @throws JAXBException
 */
public Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext lcontext = getJAXBContext();
    Unmarshaller u = lcontext.createUnmarshaller();
    if (unmarshalListener != null) {
        u.setListener(unmarshalListener);
    }
    if (novalidate) {
        u.setEventHandler(new ValidationEventHandler() {
            @Override
            public boolean handleEvent(ValidationEvent event) {
                return true;
            }
        });
    }
    return u;
}