Example usage for javax.xml.validation Schema newValidator

List of usage examples for javax.xml.validation Schema newValidator

Introduction

In this page you can find the example usage for javax.xml.validation Schema newValidator.

Prototype

public abstract Validator newValidator();

Source Link

Document

Creates a new Validator for this Schema .

Usage

From source file:org.openhab.tools.analysis.checkstyle.EshInfXmlValidationCheck.java

private void validateXmlAgainstSchema(File xmlFile, Schema schema) {
    if (schema != null) {
        try {// w w  w .  j  a  v  a 2 s.  c o  m
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(xmlFile));
        } catch (SAXParseException exception) {
            String message = exception.getMessage();
            // Removing the type of the logged message (For example - "cvc-complex-type.2.4.b: ...").
            message = message.substring(message.indexOf(":") + 2);
            int lineNumber = exception.getLineNumber();
            log(lineNumber, message, xmlFile.getPath());
        } catch (IOException | SAXException e) {
            logger.error("Problem occurred while parsing the file " + xmlFile.getName(), e);
        }
    } else {
        logger.warn("XML validation will be skipped as the schema file download failed.");
    }
}

From source file:org.openmainframe.ade.main.AdeUtilMain.java

protected void validateGood(File file) throws IOException, SAXException, AdeException {
    System.out.println("Starting");

    String fileName_Flowlayout_xsd = Ade.getAde().getConfigProperties().getXsltDir()
            + FLOW_LAYOUT_XSD_File_Name;
    Source schemaFile = new StreamSource(fileName_Flowlayout_xsd);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema mSchema = sf.newSchema(schemaFile);

    System.out.println("Validating " + file.getPath());
    Validator val = mSchema.newValidator();
    FileInputStream fis = new FileInputStream(file);
    StreamSource streamSource = new StreamSource(fis);

    try {//ww w. ja v  a  2s  .c  om
        val.validate(streamSource);
    } catch (SAXParseException e) {
        System.out.println(e);
        throw e;
    }
    System.out.println("SUCCESS!");
}

From source file:org.openmrs.module.radiology.report.template.XsdMrrtReportTemplateValidator.java

/**
 * @see MrrtReportTemplateValidator#validate(String)
 *//*w  w w. j a v a2 s . c o  m*/
@Override
public void validate(String mrrtTemplate) throws IOException {

    final Document document = Jsoup.parse(mrrtTemplate, "");
    final Elements metatags = document.getElementsByTag("meta");
    ValidationResult validationResult = metaTagsValidationEngine.run(metatags);

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    final Validator validator;
    try (InputStream in = IOUtils.toInputStream(mrrtTemplate)) {
        schema = factory.newSchema(getSchemaFile());
        validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }
        });
        validator.validate(new StreamSource(in));
        validationResult.assertOk();
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
        throw new APIException("radiology.report.template.validation.error", null, e);
    }
}

From source file:org.opennms.core.test.xml.XmlTest.java

protected void validateXmlString(final String xml) throws Exception {
    if (getSchemaFile() == null) {
        LOG.warn("skipping validation, schema file not set");
        return;//from  w  w w.  j a va2s .  co m
    }

    final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final File schemaFile = new File(getSchemaFile());
    LOG.debug("Validating using schema file: {}", schemaFile);
    final Schema schema = schemaFactory.newSchema(schemaFile);

    final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setValidating(true);
    saxParserFactory.setNamespaceAware(true);
    saxParserFactory.setSchema(schema);

    assertTrue("make sure our SAX implementation can validate", saxParserFactory.isValidating());

    final Validator validator = schema.newValidator();
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    final Source source = new StreamSource(inputStream);

    validator.validate(source);
}

From source file:org.opentestsystem.delivery.AccValidator.handlers.ValidationHandler.java

private void validateAgainstXSD(InputStream xml, InputStream xsd) throws ValidationException {
    try {//from w w  w  .  j  a va 2s . c o  m
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));

    } catch (Exception ex) {
        throw new ValidationException("failed", "Failed against schema. Error message:" + ex.getMessage());
    }
}

From source file:org.orcid.core.cli.ManageClientGroup.java

private Validator createValidator() {
    try {//from w w w . ja va 2 s  .co  m
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Schema schema = factory.newSchema(getClass().getResource("/orcid-client-group-1.3.xsd"));
        return schema.newValidator();
    } catch (SAXException e) {
        throw new RuntimeException("Error reading ORCID client group schema", e);
    }
}

From source file:org.pentaho.di.job.entries.xsdvalidator.JobEntryXSDValidator.java

public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);/*from w  w  w  .j a v a2 s . co m*/

    String realxmlfilename = getRealxmlfilename();
    String realxsdfilename = getRealxsdfilename();

    FileObject xmlfile = null;
    FileObject xsdfile = null;

    try {

        if (xmlfilename != null && xsdfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename, this);
            xsdfile = KettleVFS.getFileObject(realxsdfilename, this);

            if (xmlfile.exists() && xsdfile.exists()) {

                SchemaFactory factorytXSDValidator_1 = SchemaFactory
                        .newInstance("http://www.w3.org/2001/XMLSchema");

                // Get XSD File
                File XSDFile = new File(KettleVFS.getFilename(xsdfile));
                Schema SchematXSD = factorytXSDValidator_1.newSchema(XSDFile);

                Validator XSDValidator = SchematXSD.newValidator();

                // Get XML File
                File xmlfiletXSDValidator_1 = new File(KettleVFS.getFilename(xmlfile));

                Source sourcetXSDValidator_1 = new StreamSource(xmlfiletXSDValidator_1);

                XSDValidator.validate(sourcetXSDValidator_1);

                // Everything is OK
                result.setResult(true);

            } else {

                if (!xmlfile.exists()) {
                    logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist1.Label")
                            + realxmlfilename
                            + BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                if (!xsdfile.exists()) {
                    logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist1.Label")
                            + realxsdfilename
                            + BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    } catch (SAXException ex) {
        logError("Error :" + ex.getMessage());
    } catch (Exception e) {

        logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXSDValidator.Label")
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXML1.Label") + realxmlfilename
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXML2.Label")
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXSD1.Label") + realxsdfilename
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXSD2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }

            if (xsdfile != null) {
                xsdfile.close();
            }

        } catch (IOException e) {
            // Ignore errors
        }
    }

    return result;
}

From source file:org.pentaho.di.trans.steps.xsdvalidator.XsdValidator.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XsdValidatorMeta) smi;//from  www  .j a va2 s. c  o m
    data = (XsdValidatorData) sdi;

    Object[] row = getRow();

    if (row == null) { // no more input to be expected...

        setOutputDone();
        return false;
    }

    if (first) {
        first = false;
        data.outputRowMeta = getInputRowMeta().clone();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);

        // Check if XML stream is given
        if (meta.getXMLStream() != null) {
            // Try to get XML Field index
            data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream());
            // Let's check the Field
            if (data.xmlindex < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorFindingField") + "["
                        + meta.getXMLStream() + "]");
                throw new KettleStepException(BaseMessages.getString(PKG,
                        "XsdValidator.Exception.CouldnotFindField", meta.getXMLStream()));
            }

            // Let's check that Result Field is given
            if (meta.getResultfieldname() == null) {
                // Result field is missing !
                logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorResultFieldMissing"));
                throw new KettleStepException(
                        BaseMessages.getString(PKG, "XsdValidator.Exception.ErrorResultFieldMissing"));
            }

            // Is XSD file is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
                if (meta.getXSDFilename() == null) {
                    logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorXSDFileMissing"));
                    throw new KettleStepException(
                            BaseMessages.getString(PKG, "XsdValidator.Exception.ErrorXSDFileMissing"));
                } else {
                    // Is XSD file exists ?
                    FileObject xsdfile = null;
                    try {
                        xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename()),
                                getTransMeta());
                        if (!xsdfile.exists()) {
                            logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XSDFileNotExists"));
                            throw new KettleStepException(
                                    BaseMessages.getString(PKG, "XsdValidator.Exception.XSDFileNotExists"));
                        }

                    } catch (Exception e) {
                        logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.GettingXSDFile"));
                        throw new KettleStepException(
                                BaseMessages.getString(PKG, "XsdValidator.Exception.GettingXSDFile"));
                    } finally {
                        try {
                            if (xsdfile != null) {
                                xsdfile.close();
                            }
                        } catch (IOException e) {
                            // Ignore errors
                        }
                    }
                }
            }

            // Is XSD field is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
                if (meta.getXSDDefinedField() == null) {
                    logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XSDFieldMissing"));
                    throw new KettleStepException(
                            BaseMessages.getString(PKG, "XsdValidator.Exception.XSDFieldMissing"));
                } else {
                    // Let's check if the XSD field exist
                    // Try to get XML Field index
                    data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField());

                    if (data.xsdindex < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorFindingXSDField",
                                meta.getXSDDefinedField()));
                        throw new KettleStepException(BaseMessages.getString(PKG,
                                "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField()));
                    }
                }
            }

        } else {
            // XML stream field is missing !
            logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XmlStreamFieldMissing"));
            throw new KettleStepException(
                    BaseMessages.getString(PKG, "XsdValidator.Exception.XmlStreamFieldMissing"));
        }
    }

    try {

        // Get the XML field value
        String XMLFieldvalue = getInputRowMeta().getString(row, data.xmlindex);

        boolean isvalid = false;

        // XSD filename
        String xsdfilename = null;

        if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
            xsdfilename = environmentSubstitute(meta.getXSDFilename());
        } else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
            // Get the XSD field value
            xsdfilename = getInputRowMeta().getString(row, data.xsdindex);
        }

        // Get XSD filename
        FileObject xsdfile = null;
        String validationmsg = null;
        try {

            SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            xsdfile = KettleVFS.getFileObject(xsdfilename, getTransMeta());

            // Get XML stream
            Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue));

            if (meta.getXMLSourceFile()) {

                // We deal with XML file
                // Get XML File
                File xmlfileValidator = new File(XMLFieldvalue);
                if (!xmlfileValidator.exists()) {
                    logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XMLfileMissing",
                            XMLFieldvalue));
                    throw new KettleStepException(BaseMessages.getString(PKG,
                            "XsdValidator.Exception.XMLfileMissing", XMLFieldvalue));
                }
                sourceXML = new StreamSource(xmlfileValidator);
            }

            // create the schema
            Schema SchematXSD = null;
            if (xsdfile instanceof LocalFile) {
                SchematXSD = factoryXSDValidator.newSchema(new File(KettleVFS.getFilename(xsdfile)));
            } else if (xsdfile instanceof HttpFileObject) {
                SchematXSD = factoryXSDValidator.newSchema(new URL(KettleVFS.getFilename(xsdfile)));
            } else {
                // we should not get here as anything entered in that does not look like
                // a url should be made a FileObject.
                throw new KettleStepException(BaseMessages.getString(PKG,
                        "XsdValidator.Exception.CannotCreateSchema", xsdfile.getClass().getName()));
            }

            if (meta.getXSDSource().equals(meta.NO_NEED)) {
                // ---Some documents specify the schema they expect to be validated against,
                // ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes
                // ---Schema SchematXSD = factoryXSDValidator.newSchema();
                SchematXSD = factoryXSDValidator.newSchema();
            }

            // Create XSDValidator
            Validator XSDValidator = SchematXSD.newValidator();
            // Validate XML / XSD
            XSDValidator.validate(sourceXML);

            isvalid = true;

        } catch (SAXException ex) {
            validationmsg = ex.getMessage();
        } catch (IOException ex) {
            validationmsg = ex.getMessage();
        } finally {
            try {
                if (xsdfile != null) {
                    xsdfile.close();
                }
            } catch (IOException e) {
                // Ignore errors
            }
        }

        Object[] outputRowData = null;
        Object[] outputRowData2 = null;

        if (meta.getOutputStringField()) {
            // Output type=String
            if (isvalid) {
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlValid()));
            } else {
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlInvalid()));
            }
        } else {
            outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), isvalid);
        }

        if (meta.useAddValidationMessage()) {
            outputRowData2 = RowDataUtil.addValueData(outputRowData, getInputRowMeta().size() + 1,
                    validationmsg);
        } else {
            outputRowData2 = outputRowData;
        }

        if (log.isRowLevel()) {
            logRowlevel(BaseMessages.getString(PKG, "XsdValidator.Log.ReadRow") + " "
                    + getInputRowMeta().getString(row));
        }

        // add new values to the row.
        putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s);
    } catch (KettleException e) {
        boolean sendToErrorRow = false;
        String errorMessage = null;

        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        }

        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001");
        } else {
            logError(BaseMessages.getString(PKG, "XsdValidator.ErrorProcesing" + " : " + e.getMessage()));
            throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.ErrorProcesing"), e);
        }
    }

    return true;

}

From source file:org.plasma.common.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and sream. Loads only
 * the given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * //from   w  w w. j a v a2s.  c  o m
 * @param stream
 *            the Schema stream
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(InputStream[] streams, JAXBContext context, Handler handler,
        Resolver resolver) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    StreamSource[] sources = new StreamSource[streams.length];
    for (int i = 0; i < streams.length; i++) {
        sources[i] = new StreamSource(streams[i]);
        //FIXME: will not resolve relative URI's (included schemas) without this
        //sources[i].setSystemId(systemId)
    }
    Schema schemaGrammar = schemaFactory.newSchema(sources);
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.rimudb.configuration.AbstractXmlLoader.java

/**
 * @param document//from  www  .  ja  v a 2  s . c o m
 * @param compoundDbSchemaUrl
 * @return SAXParseException
 * @throws Exception 
 */
protected SAXParseException validate(Document document, String compoundDbSchemaUrl) throws Exception {
    // Compile a schema for the XSD
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Look up the schema URL and find it's local resource file 
    URL schemaURL = null;
    String schemaPath = RimuDBNamespace.lookupInternalSchema(compoundDbSchemaUrl);
    if (schemaPath != null) {
        schemaURL = getClass().getClassLoader().getResource(schemaPath);
    } else {
        schemaURL = new URL(compoundDbSchemaUrl);
    }

    Schema schema = schemaFactory.newSchema(schemaURL);

    // Validate the document against the schema
    Validator validator = schema.newValidator();
    validator.setErrorHandler(new StrictErrorHandler());
    try {
        validator.validate(new DOMSource(document), new DOMResult());
    } catch (SAXParseException e) {
        return e;
    }

    return null;
}