Example usage for javax.xml.validation Validator validate

List of usage examples for javax.xml.validation Validator validate

Introduction

In this page you can find the example usage for javax.xml.validation Validator validate.

Prototype

public void validate(Source source) throws SAXException, IOException 

Source Link

Document

Validates the specified input.

Usage

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

private void validateXmlAgainstSchema(File xmlFile, Schema schema) {
    if (schema != null) {
        try {//from w  w  w .j  av  a 2 s . c om
            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 {//from   w w w . ja v a 2  s .  c  o m
        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)
 *///from   ww w  . ja v a 2  s  .c om
@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 v  a2  s. c  o  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 {// w w  w  .ja va 2s .  co  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 boolean isValidAgainstSchema(File fileToValidate) {
    Validator validator = createValidator();
    Source source = new StreamSource(fileToValidate);
    try {//from   www .  j  a v a2s . co m
        validator.validate(source);
        System.out.println(fileToValidate + " is valid");
        return true;
    } catch (SAXException e) {
        System.out.println(fileToValidate + " is invalid");
        System.out.println(e);
    } catch (IOException e) {
        System.out.println("Unable to read file " + fileToValidate);
    }
    return false;
}

From source file:org.orcid.core.manager.impl.ValidationManagerImpl.java

protected void doSchemaValidation(OrcidMessage orcidMessage) {
    Validator validator = createValidator();
    if (validator != null) {
        try {// w  w  w  . ja  va 2 s.com
            validator.validate(orcidMessage.toSource());
        } catch (SAXException e) {
            handleError("ORCID message is invalid", e, orcidMessage);
        } catch (IOException e) {
            handleError("Unable to read ORCID message", e, orcidMessage);
        }
    }
}

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

public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);//  ww  w . j a v a  2 s  .c o  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  w w  w . j a va2s . com*/
    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.roda.core.common.PremisV3Utils.java

public static boolean isPremisV2(Binary binary) throws IOException, SAXException {
    boolean premisV2 = true;
    InputStream inputStream = binary.getContent().createInputStream();
    InputStream schemaStream = RodaCoreFactory.getConfigurationFileAsStream("schemas/premis-v2-0.xsd");
    Source xmlFile = new StreamSource(inputStream);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
    Validator validator = schema.newValidator();
    RodaErrorHandler errorHandler = new RodaErrorHandler();
    validator.setErrorHandler(errorHandler);
    try {//from ww w  .ja  va  2s. c o  m
        validator.validate(xmlFile);
        List<SAXParseException> errors = errorHandler.getErrors();
        if (!errors.isEmpty()) {
            premisV2 = false;
        }
    } catch (SAXException e) {
        premisV2 = false;
    }
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(schemaStream);
    return premisV2;
}