Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

From source file:mx.bigdata.cfdi.CFDv3.java

public void validate(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }//from   w w w  .j  a v  a 2  s  .  co m
    validator.validate(new JAXBSource(CONTEXT, document));
}

From source file:mx.bigdata.cfdi.TFDv1.java

public void validate(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }//from   www . j a  va  2s. c om
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

From source file:module.signature.util.XAdESValidator.java

private static void loadXAdESSchemas() {
    if (schemaFactory == null) {
        schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    }/* w ww.j  a  va2  s .co m*/
    Source[] sources = new StreamSource[3];
    sources[0] = new StreamSource(
            XAdESValidator.class.getResourceAsStream("/resources/" + schemaXmldSigCoreFilename));
    sources[1] = new StreamSource(
            XAdESValidator.class.getResourceAsStream("/resources/" + schemaXAdESv132Filename));
    sources[2] = new StreamSource(
            XAdESValidator.class.getResourceAsStream("/resources/" + schemaXAdESv141Filename));
    try {
        schemaXSD = schemaFactory.newSchema(sources);
    } catch (SAXException e) {
        e.printStackTrace();
        //joantune: TODO probably should do something differente here!!
        throw new DomainException("error.loading.XADES.scheme", e);
    }

}

From source file:de.intevation.test.irixservice.UploadReportTest.java

public ReportType getReportFromFile(String file) {
    try {//from   ww w. j a va  2 s  . c  om
        JAXBContext jaxbContext = JAXBContext.newInstance(ReportType.class.getPackage().getName());

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(testObj.irixSchemaFile);

        Unmarshaller u = jaxbContext.createUnmarshaller();
        u.setSchema(schema);
        JAXBElement obj = (JAXBElement) u.unmarshal(new File(file));
        return (ReportType) obj.getValue();
    } catch (JAXBException | SAXException e) {
        log.debug("Failed to parse report test data: " + file);
        log.debug(e);
        return null;
    }
}

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

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

            //                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.motechproject.mobile.web.ivr.intellivr.IntellIVRController.java

public void init() {
    Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    try {/*from w  w w . j  a  va  2  s  .  c om*/
        Schema schema = factory.newSchema(schemaResource.getFile());
        parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        validator = schema.newValidator();
    } catch (SAXException e) {
        log.error("Error initializing controller:", e);
    } catch (IOException e) {
        log.error("Error initializing controller:", e);
    } catch (ParserConfigurationException e) {
        log.error("Error initializing controller:", e);
    } catch (FactoryConfigurationError e) {
        log.error("Error initializing controller:", e);
    }
    try {
        JAXBContext jaxbc = JAXBContext.newInstance("org.motechproject.mobile.omp.manager.intellivr");
        marshaller = jaxbc.createMarshaller();
        unmarshaller = jaxbc.createUnmarshaller();
    } catch (JAXBException e) {
        log.error("Error initializing controller:", e);
    }
}

From source file:mx.bigdata.sat.cfdi.TFDv11c33.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[XSD.length];
    for (int i = 0; i < XSD.length; i++) {
        schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
    }/*from  w  ww.j  a va 2 s  .c  om*/
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(URL xmlUrl, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;//from w w  w  .j av a  2s  . c  o m
    ValidationResult result;
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlUrl);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:com.agimatec.validation.jsr303.xml.ValidationParser.java

static Schema getSchema(String xsd) {
    ClassLoader loader = PrivilegedActions.getClassLoader(ValidationParser.class);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = loader.getResource(xsd);
    try {// w  w w  . j a v a  2 s.  co m
        return sf.newSchema(schemaUrl);
    } catch (SAXException e) {
        log.warn("Unable to parse schema: " + xsd, e);
        return null;
    }
}

From source file:com.edmunds.etm.common.xml.XmlValidator.java

/**
 * Creates schema factory, opens schema file and initializes schema rulesConfigValidator.
 *
 * @param schemaFileName XSD schema file name.
 * @return validator object./* w  w  w  .j a  v  a  2 s.  c  o m*/
 * @throws org.xml.sax.SAXException when parser error occurs.
 * @throws java.io.IOException      when IO error occurs.
 */
private Validator initValidator(String schemaFileName) throws SAXException, IOException {
    InputStream is = null;
    try {
        SchemaFactory factory = SchemaFactory.newInstance(W3_ORG_XMLSCHEMA);
        is = getClass().getResourceAsStream(schemaFileName);
        Source source = new StreamSource(is);
        Schema schema = factory.newSchema(source);
        return schema.newValidator();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}