Example usage for javax.xml.validation SchemaFactory newSchema

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

Introduction

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

Prototype

public abstract Schema newSchema(Source[] schemas) throws SAXException;

Source Link

Document

Parses the specified source(s) as a schema and returns it as a schema.

Usage

From source file:io.onedecision.engine.decisions.model.dmn.validators.SchemaValidator.java

public void validate(InputStream obj, Errors errors) {
    InputStream is = (InputStream) obj;

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LocalResourceResolver());

    try {//from ww  w  . j ava 2s  . c  o  m
        schemaFactory.newSchema(new StreamSource(getResourceAsStreamWrapper("schema/dmn.xsd")));
    } catch (SAXException e1) {
        errors.reject("Cannot find / read schema", "Exception: " + e1.getMessage());
    }

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // parserFactory.setSchema(schema);

    SAXParser parser = null;
    try {
        parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(this);

        try {
            parser.parse(new InputSource(is), (DefaultHandler) null);
        } catch (Exception e) {
            String msg = "Schema validation failed";
            LOGGER.error(msg, e);
            errors.reject(msg, "Exception: " + e.getMessage());
        }
        if (this.errors.size() > 0) {
            errors.reject("Schema validation failed", this.errors.toString());
        }
    } catch (ParserConfigurationException e1) {
        errors.reject("Cannot create parser", "Exception: " + e1.getMessage());
    } catch (SAXException e1) {
        errors.reject("Parser cannot be created", "Exception: " + e1.getMessage());
    }
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml/*from w w  w. ja  v a2  s .  c  o m*/
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:cl.vmetrix.operation.persistence.XmlValidator.java

/**
 * The method validatorXMLstg determinate if the String XML is correct. 
 * @return a boolean (true or false) to indicate if the XML is correct.
 * @param xml is the String XML to validate against XSD Schema
 * @throws SAXException//from   w w  w  .jav a  2  s  . com
 * @throws IOException
 */

public boolean validateXMLstg(String xml) throws SAXException, IOException {
    String rpta = "";

    boolean validation = true;
    try {

        xml = new String(xml.getBytes("UTF-8"));

        //         System.out.println("---> XML in UTF-8: "+ xml);
        // convert String into InputStream
        InputStream is = new ByteArrayInputStream(xml.getBytes());

        Source xmlFile = new StreamSource(is);//new File("C:/XML/424437.xml"));

        // XSD schema
        String schemea = getFileSchema("operationSchema.xsd");

        InputStream sch = new ByteArrayInputStream(schemea.getBytes());

        Source schemaFile = new StreamSource(sch);//new File("main/resources/Operation.xsd"));

        // Preparing the schema
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);

        // Validator creation
        Validator validator = schema.newValidator();

        // DException handle of validator
        final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }
        });

        // XML validation
        validator.validate(xmlFile);

        // Validation result. If there are errors, detailed the exact position in the XML  and the error
        if (exceptions.size() == 0) {
            rpta = "XML IS VALID";
        } else {
            validation = false;
            StringBuffer sb = new StringBuffer();
            sb.append("XML IS INVALID");
            sb.append("\n");
            sb.append("NUMBER OF ERRORS: " + exceptions.size());
            sb.append("\n");
            for (int i = 0; i < exceptions.size(); i++) {
                i = i + 1;
                sb.append("Error # " + i + ":");
                sb.append("\n");
                i = i - 1;
                sb.append("    - Line: " + ((SAXParseException) exceptions.get(i)).getLineNumber());
                sb.append("\n");
                sb.append("    - Column: " + ((SAXParseException) exceptions.get(i)).getColumnNumber());
                sb.append("\n");
                sb.append("    - Error message: " + ((Throwable) exceptions.get(i)).getLocalizedMessage());
                sb.append("\n");
                sb.append("------------------------------");
            }
            rpta = sb.toString();
            logger.debug(rpta);

        }
    } catch (SAXException e) {
        logger.error("SAXException in XML validator: ", e);
        logger.debug(rpta);
        throw new SAXException(e);
    } catch (IOException e) {
        logger.error("IOException in XML validator: ", e);
        logger.debug(rpta);
        throw new IOException(e);
    }

    return validation;
}

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

public ReportType getReportFromFile(String file) {
    try {/*  w ww . j  a v a2 s . c  o  m*/
        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:mx.bigdata.sat.cfd.CFDv2.java

public void validar(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 va 2 s . c  o m
    validator.validate(new JAXBSource(context, document));
}

From source file:info.raack.appliancelabeler.service.OAuthRequestProcessor.java

@PostConstruct
public void init() {
    try {//from  w  w w.j a v  a 2s. co m
        JAXBContext jc = JAXBContext.newInstance("edu.cmu.hcii.stepgreen.data.teds");
        u1 = jc.createUnmarshaller();
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = this.getClass().getClassLoader().getResource("teds.xsd");
        Schema schema = sf.newSchema(url);
        u1.setSchema(schema);

        jc = JAXBContext.newInstance("edu.cmu.hcii.stepgreen.data.base");
        u2 = jc.createUnmarshaller();
        sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        url = this.getClass().getClassLoader().getResource("stepgreen.xsd");
        schema = sf.newSchema(url);
        u2.setSchema(schema);

    } catch (Exception e) {
        throw new RuntimeException("Could not create JAXB unmarshaller", e);
    }
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Gets the <code>Schema</code> object for the provided <code>File</code>.
 * /*from  w ww .jav a2s .co m*/
 * @param schemaStream The file containing the schema.
 * @return Returns the <code>Schema</code> object.
 * @throws Exception If anything fails.
 */
private static Schema getSchema(final String schemaFileName) throws Exception {
    if (schemaFileName == null) {
        throw new IllegalArgumentException(
                TestBase.class.getSimpleName() + ":getSchema:schemaFileName is null");
    }
    File schemaFile = new File(schemaFileName);

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema theSchema = sf.newSchema(schemaFile);
    return theSchema;
}

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   ww w  .  j a  v a 2s . c o  m
        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:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java

public Schema loadSchema(String name) {
    Schema schema = null;//from  w ww .  jav a2s  .com
    try {
        String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
        SchemaFactory factory = SchemaFactory.newInstance(language);
        schema = factory.newSchema(new File(name));
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    return schema;
}