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:Main.java

/**
 * Check whether a DOM tree is valid according to a schema. Example of
 * usage://  w  w w .j  a v  a  2s  .c om
 * <pre>
 * Element fragment = ...;
 * SchemaFactory f = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 * Schema s = f.newSchema(This.class.getResource("something.xsd"));
 * try {
 *     XMLUtil.validate(fragment, s);
 *     // valid
 * } catch (SAXException x) {
 *     // invalid
 * }
 * </pre>
 *
 * @param data   a DOM tree
 * @param schema a parsed schema
 * @throws SAXException if validation failed
 * @since org.openide.util 7.17
 */
public static void validate(Element data, Schema schema) throws SAXException {
    Validator v = schema.newValidator();
    final SAXException[] error = { null };
    v.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException x) throws SAXException {
        }

        @Override
        public void error(SAXParseException x) throws SAXException {
            // Just rethrowing it is bad because it will also print it to stderr.
            error[0] = x;
        }

        @Override
        public void fatalError(SAXParseException x) throws SAXException {
            error[0] = x;
        }
    });
    try {
        v.validate(new DOMSource(fixupAttrs(data)));
    } catch (IOException x) {
        assert false : x;
    }
    if (error[0] != null) {
        throw error[0];
    }
}

From source file:Main.java

/**
 * Validates the given document with its schema.
 * /*  ww  w  .j  av  a 2  s  .  co  m*/
 * @param document - The XML file contents
 * @param schemaFileStream - the inputStream of the schema content
 * @throws Exception
 */
public static void validateDocument(Document document, InputStream schemaFileStream) throws Exception {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(schemaFileStream);
    Schema schema = factory.newSchema(schemaFile);
    // create a Validator instance, which can be used to validate an
    // instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    validator.validate(new DOMSource(document));
}

From source file:Main.java

public static void validateXml(Node root, InputStream xsd) throws SAXException, IOException {
    try {/* ww  w.j  a  v  a2s . co  m*/
        Source source = new StreamSource(xsd);
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source);

        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(root));
    } finally {
        closeStream(xsd);
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.data.QueryResultContainer.java

/**
 * Validates input XML file using 'queryResult.xsd' schema.
 *
 * @param xml xml//w ww .j av  a2  s  .co  m
 * @throws IOException if file is not valid
 */
public static void validateXML(String xml) throws IOException {
    String xsdName = "queryResult.xsd";
    URL resource = QueryResultContainer.class.getClass().getResource(xsdName);
    if (resource == null) {
        throw new IllegalStateException("Cannot locate resource " + xsdName + " on classpath");
    }

    URL xsdFile;
    try {
        xsdFile = resource.toURI().toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        throw new IOException(e);
    }

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Schema schema = factory.newSchema(xsdFile);
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new StringReader(xml)));
    } catch (SAXException e) {
        throw new IOException(e);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java

/**
 * Validates configuration XML against XML defined XSD schema.
 *
 * @param config//from   w w  w.j av  a2  s  .  c  om
 *            {@link InputStream} to get configuration data from
 * @return map of found validation errors
 * @throws SAXException
 *             if there was an error parsing the configuration
 * @throws IOException
 *             if there is an error reading the configuration data
 */
public static Map<OpLevel, List<SAXParseException>> validate(InputStream config)
        throws SAXException, IOException {
    final Map<OpLevel, List<SAXParseException>> validationErrors = new HashMap<>();
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema();
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.WARNING, exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.ERROR, exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.FATAL, exception);
            }

            private void handleValidationError(OpLevel level, SAXParseException exception) {
                List<SAXParseException> lErrorsList = validationErrors.get(level);
                if (lErrorsList == null) {
                    lErrorsList = new ArrayList<>();
                    validationErrors.put(level, lErrorsList);
                }

                lErrorsList.add(exception);
            }
        });
        validator.validate(new StreamSource(config));
    } finally {
        if (config.markSupported()) {
            config.reset();
        }
    }

    return validationErrors;
}

From source file:com.aol.advertising.qiao.util.XmlConfigUtil.java

/**
 * Validate an XML document against the given schema.
 *
 * @param xmlFileLocationUri/*from w w w. java2  s .c o  m*/
 *            Location URI of the document to be validated.
 * @param schemaLocationUri
 *            Location URI of the XML schema in W3C XML Schema Language.
 * @return true if valid, false otherwise.
 */
public static boolean validateXml(String xmlFileLocationUri, String schemaLocationUri) {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    InputStream is = null;
    try {
        Schema schema = factory.newSchema(CommonUtils.uriToURL(schemaLocationUri));
        Validator validator = schema.newValidator();
        URL url = CommonUtils.uriToURL(xmlFileLocationUri);
        is = url.openStream();
        Source source = new StreamSource(is);

        validator.validate(source);
        logger.info(">> successfully validated configuration file: " + xmlFileLocationUri);

        return true;
    } catch (SAXParseException e) {
        logger.error(e.getMessage() + " (line:" + e.getLineNumber() + ", col:" + e.getColumnNumber() + ")");

    } catch (Exception e) {
        if (e instanceof SAXParseException) {
            SAXParseException e2 = (SAXParseException) e;
            logger.error(e2.getMessage() + "at line:" + e2.getLineNumber() + ", col:" + e2.getColumnNumber());
        } else {
            logger.error(e.getMessage());
        }
    } finally {
        IOUtils.closeQuietly(is);
    }

    return false;
}

From source file:gov.nih.nci.cabig.caaers.utils.XmlValidator.java

public static boolean validateAgainstSchema(String xmlContent, String xsdUrl, StringBuffer validationResult) {
    boolean validXml = false;
    try {//from w w w.ja  va  2s. co  m
        // parse an XML document into a DOM tree
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(false);
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
        Document document = parser.parse(new InputSource(new StringReader(xmlContent)));

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // load a WXS schema, represented by a Schema instance
        Source schemaFile = new StreamSource(getResources(xsdUrl)[0].getFile());

        Schema schema = schemaFactory.newSchema(schemaFile);
        // create a Validator instance, which can be used to validate an instance document
        Validator validator = schema.newValidator();
        // validate the DOM tree
        validator.validate(new DOMSource(document));
        validXml = true;
    } catch (FileNotFoundException ex) {
        throw new CaaersSystemException("File Not found Exception", ex);
    } catch (IOException ioe) {
        validationResult.append(ioe.getMessage());
        logger.error(ioe.getMessage());
    } catch (SAXParseException spe) {
        validationResult.append("Line : " + spe.getLineNumber() + " - " + spe.getMessage());
        logger.error("Line : " + spe.getLineNumber() + " - " + spe.getMessage());
    } catch (SAXException e) {
        validationResult.append(e.toString());
        logger.error(e.toString());
    } catch (ParserConfigurationException pce) {
        validationResult.append(pce.getMessage());
    }
    return validXml;
}

From source file:org.psikeds.knowledgebase.xml.impl.XSDValidator.java

/**
 * Validate XML against specified XSD schmema.<br>
 * <b>Note:</b> The XML source/stream will not be closed. This must be
 * invoked by the caller afterwards!<br>
 * // w  w w .  j a  v  a 2 s . c o  m
 * @param xsd
 *          Source for XSD-schema that will be used to validate the XML
 * @param xml
 *          Source for XML
 * @throws SAXException
 *           if XML is not valid against XSD
 * @throws IOException
 */
public static void validate(final Source xsd, final Source xml) throws SAXException, IOException {
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = factory.newSchema(xsd);
    final Validator validator = schema.newValidator();
    validator.validate(xml);
}

From source file:eu.delving.x3ml.X3MLEngine.java

public static List<String> validateStream(InputStream inputStream) throws SAXException, IOException {
    Schema schema = schemaFactory().newSchema(new StreamSource(inputStream("x3ml_v1.0.xsd")));
    Validator validator = schema.newValidator();
    final List<String> errors = new ArrayList<String>();
    validator.setErrorHandler(new ErrorHandler() {
        @Override/* www.  j a  v  a 2s.  c om*/
        public void warning(SAXParseException exception) throws SAXException {
            errors.add(errorMessage(exception));
        }

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

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            errors.add(errorMessage(exception));
        }
    });
    StreamSource source = new StreamSource(inputStream);
    validator.validate(source);
    return errors;
}

From source file:dk.netarkivet.common.utils.XmlUtils.java

/**
 * Validate that the settings xml files conforms to the XSD.
 *
 * @param xsdFile Schema to check settings against.
 * @throws ArgumentNotValid if unable to validate the settings files
 * @throws IOFailure If unable to read the settings files and/or 
 * the xsd file./*w  w  w.j a  v a 2s. co  m*/
 */
public static void validateWithXSD(File xsdFile) {
    ArgumentNotValid.checkNotNull(xsdFile, "File xsdFile");
    List<File> settingsFiles = Settings.getSettingsFiles();
    for (File settingsFile : settingsFiles) {
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            builderFactory.setNamespaceAware(true);
            DocumentBuilder parser = builderFactory.newDocumentBuilder();
            org.w3c.dom.Document document = parser.parse(settingsFile);

            // create a SchemaFactory capable of understanding WXS schemas
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // load a WXS schema, represented by a Schema instance
            Source schemaFile = new StreamSource(xsdFile);
            Schema schema = factory.newSchema(schemaFile);

            // create a Validator instance, which can be used to validate an
            // instance document
            Validator validator = schema.newValidator();

            // validate the DOM tree
            try {
                validator.validate(new DOMSource(document));
            } catch (SAXException e) {
                // instance document is invalid!
                final String msg = "Settings file '" + settingsFile + "' does not validate using '" + xsdFile
                        + "'";
                log.warn(msg, e);
                throw new ArgumentNotValid(msg, e);
            }
        } catch (IOException e) {
            throw new IOFailure("Error while validating: ", e);
        } catch (ParserConfigurationException e) {
            final String msg = "Error validating settings file '" + settingsFile + "'";
            log.warn(msg, e);
            throw new ArgumentNotValid(msg, e);
        } catch (SAXException e) {
            final String msg = "Error validating settings file '" + settingsFile + "'";
            log.warn(msg, e);
            throw new ArgumentNotValid(msg, e);
        }
    }
}