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:com.github.woozoo73.ht.XmlUtils.java

public static boolean validate(String xsd, String xml) {
    try {/*w ww  .jav a 2  s.  co  m*/
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Schema schema = factory.newSchema(new StreamSource(new ByteArrayInputStream(xsd.getBytes("UTF-8"))));
        Validator validator = schema.newValidator();

        boolean valid = false;
        try {
            validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));
            valid = true;
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }

        return valid;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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 www  . j  ava  2s.c o 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:de.tudarmstadt.ukp.experiments.dip.wp1.data.QueryResultContainer.java

/**
 * Validates input XML file using 'queryResult.xsd' schema.
 *
 * @param xml xml//from  w  w  w . j  a  v a  2 s. com
 * @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:Main.java

public static boolean xmlStringValidate(String xmlStr, String xsdPath) {
    boolean flag = false;
    try {/*  w ww . j a va2 s  .c o m*/
        SchemaFactory factory = SchemaFactory.newInstance(SCHEMALANG);
        File schemaLocation = new File(xsdPath);
        Schema schema = factory.newSchema(schemaLocation);
        Validator validator = schema.newValidator();
        InputStream is = new ByteArrayInputStream(xmlStr.getBytes());
        Source source = new StreamSource(is);
        try {
            validator.validate(source);
            flag = true;
        } catch (SAXException ex) {
            System.out.println(ex.getMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return flag;
}

From source file:Main.java

public static boolean validate(URL schemaFile, String xmlString) {
    boolean success = false;
    try {//from  ww w . j  ava 2 s.  c o m
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();
        Source xmlSource = null;
        try {
            xmlSource = new StreamSource(new java.io.StringReader(xmlString));
            validator.validate(xmlSource);
            System.out.println("Congratulations, the document is valid");
            success = true;
        } catch (SAXException e) {
            e.printStackTrace();
            System.out.println(xmlSource.getSystemId() + " is NOT valid");
            System.out.println("Reason: " + e.getLocalizedMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return success;
}

From source file:Main.java

/**
 * Check a xml file against a schema.//www . j a v  a2  s  . co  m
 * 
 * @param fileToCheck
 * @param schemURL
 * @throws Exception
 */
static public void schemaCheck(File fileToCheck, URL schemURL) throws Exception {

    final String W3C_SCHEMA_SPEC = "http://www.w3.org/2001/XMLSchema";
    HashMap<String, Schema> MetsSchema = null;

    if (MetsSchema == null) {
        MetsSchema = new HashMap();
    }

    if (MetsSchema.get(schemURL.toString()) == null) {
        // 1. Lookup a factory for the W3C XML Schema language
        SchemaFactory factory = SchemaFactory.newInstance(W3C_SCHEMA_SPEC);

        // 2. Compile the schema. 
        MetsSchema.put(schemURL.toString(), factory.newSchema(schemURL));
    }

    // 3. Get a validator from the schema.
    Validator validator = MetsSchema.get(schemURL.toString()).newValidator();

    // 4. Parse the document you want to check.
    Source source = new StreamSource(fileToCheck);

    // 5. Check the document        
    validator.validate(source);
}

From source file:de.fhg.iais.model.aip.util.XmlUtilsTest.java

private static Document parseAndValidate(String xml, URL xsd) {
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;/* w w w  . j a  va2s. c  om*/
    try {
        schema = factory.newSchema(xsd);
    } catch (final SAXException e) {
        throw new DbcException(e);
    }

    //        final Document xmlDocument = XmlUtils.parse(xml);
    final Document xmlDocument = XmlProcessor.buildDocumentFrom(xml);
    final Validator validator = schema.newValidator();
    try {
        validator.validate(new JDOMSource(xmlDocument));
        return xmlDocument;
    } catch (final SAXException e) {
        throw new DbcException(e);
    } catch (final IOException e) {
        throw new DbcException(e);
    }
}

From source file:Main.java

public static void validate(String xmlFileName, String schemaFileName)
        throws IOException, ParserConfigurationException, SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new File(schemaFileName));
    Validator validator = schema.newValidator();

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder parser = builderFactory.newDocumentBuilder();
    Document document = parser.parse(new File(xmlFileName));
    validator.validate(new DOMSource(document));
}

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

/**
 * Validate an XML document against the given schema.
 *
 * @param xmlFileLocationUri// w ww  .j av  a2  s  .  co 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: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  . com
 */
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);
        }
    }
}