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: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 www.  j  a v a2  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. ja va 2 s .co  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  ww . j av a  2  s. c o  m*/
        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.modeldriven.fuml.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and URL. Loads only the
 * given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * //  www . j  a  v a 2s . c  o m
 * @param url
 *            the Schema URL
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(URL url, JAXBContext context, Handler handler, Resolver resolver)
        throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    // adds a custom object factory
    // u.setProperty("com.sun.xml.bind.ObjectFactory",new
    // ObjectFactoryEx());
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(url);
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.modeldriven.fuml.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and sream. Loads only
 * the given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * //from  w  w  w  .  j a va  2s.c  om
 * @param stream
 *            the Schema stream
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(InputStream stream, JAXBContext context, Handler handler,
        Resolver resolver) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(new StreamSource(stream));
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.mule.config.spring.AbstractSchemaValidationTestCase.java

protected void doTest(String config) throws SAXException, IOException {
    try {// w w w.ja va 2 s  .  co  m
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        Schema schema = schemaFactory.newSchema(getSchemasAsSources());
        schema.newValidator().validate(load(config));
    } catch (SAXParseException ex) {
        System.err.println(MessageFormat.format("SAX parsing exception occurs at line {0}, column {1}",
                ex.getLineNumber(), ex.getColumnNumber()));
        throw ex;
    }
}

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

/**
 * @param f the xml file/* w w  w .  j  a  v a 2 s . co m*/
 * @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   www . ja  v a  2s . 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.
  * /*  ww w  .java2s  .com*/
  * @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;
    }
}

From source file:org.openehealth.ipf.commons.xml.XsdValidator.java

/**
 * @param message/* w  w w .j a v a2  s  . c  om*/
 *            the message to be validated
 * @param schemaSource
 *            the XML schema to validate against
 * @return an array of validation exceptions
 */
protected List<ValidationException> doValidate(Source message, String schemaResource) {
    try {
        LOG.debug("Validating XML message");
        Schema schema = obtainSchema(schemaResource);
        javax.xml.validation.Validator validator = schema.newValidator();
        CollectingErrorHandler errorHandler = new CollectingErrorHandler();
        validator.setErrorHandler(errorHandler);
        validator.validate(message);
        List<ValidationException> exceptions = errorHandler.getExceptions();
        if (exceptions.size() > 0) {
            LOG.debug("Message validation found " + exceptions.size() + " problems");
        } else {
            LOG.debug("Message validation successful");
        }
        return exceptions;
    } catch (SAXException e) {
        return Arrays
                .asList(new ValidationException("Unexpected validation failure because " + e.getMessage(), e));
    } catch (IOException e) {
        return Arrays
                .asList(new ValidationException("Unexpected validation failure because " + e.getMessage(), e));
    }
}