Example usage for javax.xml.validation Validator setErrorHandler

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

Introduction

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

Prototype

public abstract void setErrorHandler(ErrorHandler errorHandler);

Source Link

Document

Sets the ErrorHandler to receive errors encountered during the validate method invocation.

Usage

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 {/*w  w w. jav  a 2s .c  om*/
        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;
}

From source file:org.roda.core.common.validation.ValidationUtils.java

/**
 * Validates descriptive medatada (e.g. against its schema, but other
 * strategies may be used)//ww w. j ava  2s  . c  o m
 * 
 * @param descriptiveMetadataType
 * 
 * @param failIfNoSchema
 * @throws ValidationException
 */
public static ValidationReport validateDescriptiveBinary(ContentPayload descriptiveMetadataPayload,
        String descriptiveMetadataType, String descriptiveMetadataVersion, boolean failIfNoSchema) {
    ValidationReport ret = new ValidationReport();
    InputStream inputStream = null;
    Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema(descriptiveMetadataType,
            descriptiveMetadataVersion);
    try {
        if (xmlSchema.isPresent()) {
            RodaErrorHandler errorHandler = new RodaErrorHandler();

            try (InputStreamReader inputStreamReader = new InputStreamReader(
                    new BOMInputStream(descriptiveMetadataPayload.createInputStream()))) {

                XMLReader xmlReader = XMLReaderFactory.createXMLReader();
                xmlReader.setEntityResolver(new RodaEntityResolver());
                InputSource inputSource = new InputSource(inputStreamReader);
                Source source = new SAXSource(xmlReader, inputSource);

                Validator validator = xmlSchema.get().newValidator();

                validator.setErrorHandler(errorHandler);

                validator.validate(source);
                ret.setValid(errorHandler.getErrors().isEmpty());
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    ret.addIssue(convertSAXParseException(saxParseException));
                }
            } catch (SAXException e) {
                LOGGER.debug("Error validating descriptive binary " + descriptiveMetadataType, e);
                ret.setValid(false);
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    ret.addIssue(convertSAXParseException(saxParseException));
                }
            }
        } else {
            if (failIfNoSchema) {
                LOGGER.error(
                        "Will fail validating descriptive metadata with type '{}' and version '{}' because couldn't find its schema",
                        descriptiveMetadataType, descriptiveMetadataVersion);
                ret.setValid(false);
                ret.setMessage("No schema to validate " + descriptiveMetadataType);
            } else {
                LOGGER.debug(
                        "Found no schema do validate descriptive metadata but will try to validate XML syntax...");
                ret = isXMLValid(descriptiveMetadataPayload);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Error validating descriptive metadata", e);
        ret.setValid(false);
        ret.setMessage(e.getMessage());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    return ret;

}

From source file:org.roda.core.common.validation.ValidationUtils.java

/**
 * Validates preservation medatada (e.g. against its schema, but other
 * strategies may be used)/*w w  w.  jav  a2 s. co  m*/
 * 
 * @param failIfNoSchema
 * 
 * @param descriptiveMetadataId
 * 
 * @param failIfNoSchema
 * @throws ValidationException
 */
public static ValidationReport validatePreservationBinary(Binary binary, boolean failIfNoSchema) {
    ValidationReport report = new ValidationReport();
    InputStream inputStream = null;
    try {
        Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema("premis-v2-0", null);
        if (xmlSchema.isPresent()) {
            inputStream = binary.getContent().createInputStream();
            Source xmlFile = new StreamSource(inputStream);
            Validator validator = xmlSchema.get().newValidator();
            RodaErrorHandler errorHandler = new RodaErrorHandler();
            validator.setErrorHandler(errorHandler);
            try {
                validator.validate(xmlFile);
                report.setValid(errorHandler.getErrors().isEmpty());
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    report.addIssue(convertSAXParseException(saxParseException));
                }
            } catch (SAXException e) {
                LOGGER.error("Error validating preservation binary " + binary.getStoragePath(), e);
                report.setValid(false);
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    report.addIssue(convertSAXParseException(saxParseException));
                }
            }
        } else if (failIfNoSchema) {
            report.setValid(false);
            report.setMessage("No schema to validate PREMIS");
        }

    } catch (IOException e) {
        report.setValid(false);
        report.setMessage(e.getMessage());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return report;

}

From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl.java

private static void parseAndValidate(EdfiRecordParserImpl parser, Schema schema) throws XmlParseException {

    Validator validator = schema.newValidator();
    validator.setErrorHandler(parser);

    try {/*from  w w w . j  a  va  2 s  .c om*/
        validator.validate(new StAXSource(parser));
    } catch (SAXException e) {
        throw new XmlParseException("Exception while processing the xml file", e);
    } catch (IOException e) {
        throw new XmlParseException("Exception while accessing the xml file", e);
    } catch (XMLStreamException e) {
        throw new XmlParseException("Exception while processing the xml file", e);
    }
}

From source file:org.sonar.plugins.xml.checks.XmlSchemaCheck.java

private void validate(String[] schemaList) {

    // Create a new validator
    Validator validator = createSchema(schemaList).newValidator();
    setFeature(validator, Constants.XERCES_FEATURE_PREFIX + "continue-after-fatal-error", true);
    validator.setErrorHandler(new MessageHandler());
    validator.setResourceResolver(new SchemaResolver());

    // Validate and catch the exceptions. MessageHandler will receive the errors and warnings.
    try {//from w ww  .  j  a v a  2s  .  co m
        LOG.info("Validate " + getWebSourceCode() + " with schema " + StringUtils.join(schemaList, ","));
        validator.validate(new StreamSource(getWebSourceCode().createInputStream()));
    } catch (SAXException e) {
        if (!containsMessage(e)) {
            createViolation(0, e.getMessage());
        }
    } catch (IOException e) {
        throw new SonarException(e);
    } catch (UnrecoverableParseError e) {
        // ignore, message already reported.
    }
}

From source file:org.xsystem.bpmn2.formats.xml.XMLParser3.java

Document validate(InputStream input) throws ParserConfigurationException, SAXException, IOException {
    Schema schema = buildSxema();
    Validator validator = schema.newValidator();

    validator.setErrorHandler(new ErrorHandler() {

        @Override//from   ww  w . ja  va2  s.  com
        public void warning(SAXParseException ex) throws SAXException {
            System.err.println(ex.getMessage());
        }

        @Override
        public void error(SAXParseException ex) throws SAXException {
            System.err.println(ex.getMessage());
        }

        @Override
        public void fatalError(SAXParseException ex) throws SAXException {
            throw ex;
        }

    });

    Document doc = XMLUtil.getDocument(input);

    DOMSource source = new DOMSource(doc);

    validator.validate(source);//, result);

    return doc;
}