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.kuali.kfs.module.ar.batch.CustomerLoadXMLSchemaTest.java

/**
 * Validates the xml contents against the batch input type schema using the java 1.5 validation package.
 * //w w w.  j av a 2s  . c  om
 * @param schemaLocation - location of the schema file
 * @param fileContents - xml contents to validate against the schema
 */
private void validateContentsAgainstSchema(InputStream schemaLocation, InputStream fileContents)
        throws ParseException, MalformedURLException, IOException, SAXException {
    // 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 schemaSource = null;
    schemaSource = new StreamSource(schemaLocation);

    Schema schema = null;
    schema = factory.newSchema(schemaSource);

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

    // validate
    validator.validate(new StreamSource(fileContents));
}

From source file:org.kuali.kfs.module.tem.batch.PerDiemXmlInputFileType.java

/**
 * @see org.kuali.kfs.sys.batch.XmlBatchInputFileTypeBase#validateContentsAgainstSchema(java.lang.String, java.io.InputStream)
 *//*  w  w  w.  ja va  2s  .c  om*/
@Override
protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents)
        throws ParseException {

    try {
        // get schemaFile
        UrlResource schemaResource = new UrlResource(schemaLocation);

        // load a WXS schema, represented by a Schema instance
        Source schemaSource = new StreamSource(schemaResource.getInputStream());

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

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

        Source source = this.transform(fileContents);
        validator.validate(source);
    } catch (MalformedURLException e2) {
        LOG.error("error getting schema url: " + e2.getMessage());
        throw new RuntimeException("error getting schema url:  " + e2.getMessage(), e2);
    } catch (SAXException e) {
        LOG.error("error encountered while parsing xml " + e.getMessage());
        throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e);
    } catch (IOException e1) {
        LOG.error("error occured while validating file contents: " + e1.getMessage());
        throw new RuntimeException("error occurred while validating file contents: " + e1.getMessage(), e1);
    }
}

From source file:org.kuali.kfs.sys.batch.XmlBatchInputFileTypeBase.java

/**
 * Validates the xml contents against the batch input type schema using the java 1.5 validation package.
 * /*from www . ja  v a2s  .c o m*/
 * @param schemaLocation - location of the schema file
 * @param fileContents - xml contents to validate against the schema
 */
protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents)
        throws ParseException {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // get schemaFile
    Resource schemaResource = SpringContext.getResource(schemaLocation);

    // load a WXS schema, represented by a Schema instance
    Source schemaSource = null;
    try {
        schemaSource = new StreamSource(schemaResource.getInputStream());
    } catch (IOException e2) {
        LOG.error("error getting schema stream from url: " + e2.getMessage());
        throw new RuntimeException("error getting schema stream from url:   " + e2.getMessage(), e2);
    }

    Schema schema = null;
    try {
        schema = factory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("error occured while setting schema file: " + e.getMessage());
        throw new RuntimeException("error occured while setting schema file: " + e.getMessage(), e);
    }

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

    // validate
    try {
        validator.validate(new StreamSource(fileContents));
    } catch (SAXException e) {
        LOG.error("error encountered while parsing xml " + e.getMessage());
        throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e);
    } catch (IOException e1) {
        LOG.error("error occured while validating file contents: " + e1.getMessage());
        throw new RuntimeException("error occured while validating file contents: " + e1.getMessage(), e1);
    }
}

From source file:org.kuali.ole.ingest.KrmsXMLSchemaValidator.java

/**
 *  This method return True/False./*from   www . j  a  v  a 2  s  .co  m*/
 *  This method checks fileContent schema with W3 Xml schema standards,If it matches it return True else return False.
 * @param inputStream
 * @return  boolean
 * @throws org.kuali.ole.exception.ParseException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public boolean validateContentsAgainstSchema(InputStream inputStream)
        throws ParseException, IOException, SAXException {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source schemaSource = null;
        schemaSource = new StreamSource(getFileContents());
        Schema schema = null;
        schema = factory.newSchema(schemaSource);
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new XmlErrorHandler());
        validator.validate(new StreamSource(inputStream));
        return true;
    } catch (Exception ex) {
        //TODO: logging required
    }
    return false;
}

From source file:org.kuali.ole.sys.batch.XmlBatchInputFileTypeBase.java

/**
 * Validates the xml contents against the batch input type schema using the java 1.5 validation package.
 * //from w w  w .jav a  2  s. co m
 * @param schemaLocation - location of the schema file
 * @param fileContents - xml contents to validate against the schema
 */
protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents)
        throws ParseException {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // get schemaFile
    UrlResource schemaResource = null;
    try {
        schemaResource = new UrlResource(schemaLocation);
    } catch (MalformedURLException e2) {
        LOG.error("error getting schema url: " + e2.getMessage());
        throw new RuntimeException("error getting schema url:  " + e2.getMessage(), e2);
    }

    // load a WXS schema, represented by a Schema instance
    Source schemaSource = null;
    try {
        schemaSource = new StreamSource(schemaResource.getInputStream());
    } catch (IOException e2) {
        LOG.error("error getting schema stream from url: " + e2.getMessage());
        throw new RuntimeException("error getting schema stream from url:   " + e2.getMessage(), e2);
    }

    Schema schema = null;
    try {
        schema = factory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("error occured while setting schema file: " + e.getMessage());
        throw new RuntimeException("error occured while setting schema file: " + e.getMessage(), e);
    }

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

    // validate
    try {
        validator.validate(new StreamSource(fileContents));
    } catch (SAXException e) {
        LOG.error("error encountered while parsing xml " + e.getMessage());
        throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e);
    } catch (IOException e1) {
        LOG.error("error occured while validating file contents: " + e1.getMessage());
        throw new RuntimeException("error occured while validating file contents: " + e1.getMessage(), e1);
    }
}

From source file:org.lilyproject.indexer.model.indexerconf.LilyIndexerConfBuilder.java

private void validate(Document document) throws IndexerConfException {
    try {/*from w w  w  . j av  a 2s  . c o  m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = getClass().getClassLoader()
                .getResource("org/lilyproject/indexer/model/indexerconf/indexerconf.xsd");
        Schema schema = factory.newSchema(url);
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (Exception e) {
        throw new IndexerConfException("Error validating indexer configuration against XML Schema.", e);
    }
}

From source file:org.lilyproject.indexer.model.indexerconf.LilyIndexerConfBuilder.java

public static void validate(InputStream is) throws IndexerConfException {
    MyErrorHandler errorHandler = new MyErrorHandler();

    try {//from  w  w  w.ja  va  2s.  c  om
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = LilyIndexerConfBuilder.class.getClassLoader()
                .getResource("org/lilyproject/indexer/model/indexerconf/indexerconf.xsd");
        Schema schema = factory.newSchema(url);
        Validator validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(new StreamSource(is));
    } catch (Exception e) {
        if (!errorHandler.hasErrors()) {
            throw new IndexerConfException("Error validating indexer configuration.", e);
        } // else it will be reported below
    }

    if (errorHandler.hasErrors()) {
        throw new IndexerConfException("The following errors occurred validating the indexer configuration:\n"
                + errorHandler.getMessage());
    }
}

From source file:org.n52.ifgicopter.spf.xml.XMLTools.java

/**
 * @param f the xml file/*from   w  w w  . ja  v  a2s. com*/
 * @return the parsed {@link Document}
 */
public static Document parseDocument(File f) {
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = fac.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        log.warn(null, e);
        return null;
    }

    //get the config as Document
    Document doc = null;
    try {
        doc = builder.parse(f);
    } catch (SAXException e) {
        log.warn(null, e);
        return null;
    } catch (IOException e) {
        log.warn(null, e);
        return null;
    }

    /*
     * do we validate?
     */
    if (!Boolean.parseBoolean(SPFRegistry.getInstance().getConfigProperty(SPFRegistry.VALIDATE_XML_PROP))) {
        return doc;
    }

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

    Schema schema = null;
    try {
        schema = factory.newSchema();
    } catch (SAXException e) {
        log.warn(null, e);
        return null;
    }

    Validator val = schema.newValidator();
    val.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException exception) throws SAXException {
            log.warn(null, exception);
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            log.warn(null, exception);
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            warning(exception);
        }
    });

    /*
     * do the validation
     */
    try {
        val.validate(new SAXSource(new InputSource(new FileInputStream(f))));
    } catch (FileNotFoundException e) {
        log.warn(null, e);
        return null;
    } catch (SAXException e) {
        log.warn(null, e);
        return null;
    } catch (IOException e) {
        log.warn(null, e);
        return null;
    }

    return doc;
}

From source file:org.ojbc.util.xml.XmlUtils.java

public static Document validateInstance(String rootXsdPath, Document docXmlToValidate,
        IEPDFullPathResourceResolver fullPathResolver, List<String> additionalSchemaRelativePaths)
        throws Exception {

    List<String> schemaPaths = new ArrayList<String>();
    schemaPaths.add(rootXsdPath);/*from  w w  w.  ja  v  a 2 s.  c  om*/
    schemaPaths.addAll(additionalSchemaRelativePaths);

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(fullPathResolver);

    Source[] sources = new Source[schemaPaths.size()];
    int i = 0;
    for (String path : schemaPaths) {
        sources[i++] = new StreamSource(XmlUtils.class.getClassLoader().getResourceAsStream(path));
    }

    Schema schema = schemaFactory.newSchema(sources);

    Validator v = schema.newValidator();

    try {
        v.validate(new DOMSource(docXmlToValidate));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("FAILED Input Doc: \n");
            XmlUtils.printNode(docXmlToValidate);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
    return docXmlToValidate;
}

From source file:org.ojbc.util.xml.XmlUtils.java

/**
  * Validate a document against an IEPD. Note that this does not require the xsi namespace location attributes to be set in the instance.
  * /*  w  w w.j a  v  a2s .  c om*/
  * @param schemaPathList
  *            the paths to all schemas necessary to validate the instance; this is the equivalent of specifying these schemas in an xsi:schemaLocation attribute in the instance
  *                       
  * @param Never_Used_TODO_Remove 
  * 
  *            
  * @param rootSchemaFileName
  *            the name of the document/exchange schema
  * @param d
  *            the document to validate
  * @param iepdResourceResolver
  *            the resource resolver to use
  * @return the document that was validated
  * @throws Exception
  *             if the document is not valid
  */
public static void validateInstance(Document d, LSResourceResolver iepdResourceResolver,
        List<String> schemaPathList) throws SAXException, Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(iepdResourceResolver);

    List<Source> sourceList = new ArrayList<Source>();

    for (String schemaPath : schemaPathList) {

        InputStream schemaInStream = XmlUtils.class.getClassLoader().getResourceAsStream(schemaPath);

        StreamSource schemaStreamSource = new StreamSource(schemaInStream);

        sourceList.add(schemaStreamSource);
    }

    Source[] schemaSourcesArray = sourceList.toArray(new Source[] {});

    try {
        Schema schema = schemaFactory.newSchema(schemaSourcesArray);

        Validator validator = schema.newValidator();

        validator.validate(new DOMSource(d));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("Input document:");
            XmlUtils.printNode(d);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
}