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.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  .ja v  a 2 s .  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.sakaiproject.kernel.util.XSDValidator.java

/**
 * Validate a xml input stream against a supplied schema.
 * @param xml a stream containing the xml
 * @param schema a stream containing the schema
 * @return a list of errors or warnings, a 0 lenght string if none.
 *//*from   w  ww  . j a  v a2 s .c om*/
public static String validate(InputStream xml, InputStream schema) {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    final StringBuilder errors = new StringBuilder();
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
        Schema s = schemaFactory.newSchema(new StreamSource(schema));
        Validator validator = s.newValidator();
        validator.validate(new StreamSource(xml));
    } catch (IOException e) {
        errors.append(e.getMessage()).append("\n");
    } catch (SAXException e) {
        errors.append(e.getMessage()).append("\n");
    }
    return errors.toString();
}

From source file:org.sakaiproject.tool.assessment.qti.helper.AuthoringHelper.java

private boolean validateImportXml(Document doc) throws SAXException, IOException {
    // 1. Lookup a factory for the W3C XML Schema language
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    // 2. Compile the schema.
    // Here the schema is loaded from a java.io.File, but you could use
    // a java.net.URL or a javax.xml.transform.Source instead.
    String schemaFile = VALIDATE_XSD_PATH + "qtiv1p2.xsd";
    log.debug("schemaFile = " + schemaFile);
    Schema schema = factory.newSchema(
            new StreamSource(AuthoringHelper.class.getClassLoader().getResourceAsStream(schemaFile)));

    // 3. Get a validator from the schema.
    Validator validator = schema.newValidator();

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

    // 5. Check the document
    try {/* w  w  w  . j  a  v  a  2 s.com*/
        validator.validate(source);
        log.debug("The xml is valid.");
        return true;
    } catch (SAXException ex) {
        log.debug("The xml is not valid QTI format.", ex);
    }
    return false;
}

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);/*  w  w w  .  j av a2  s.  com*/

    try {
        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.tinygroup.jspengine.xmlparser.ParserUtils.java

/**
 * Parse the specified XML document, and return a <code>TreeNode</code>
 * that corresponds to the root node of the document tree.
 *
 * @param uri URI of the XML document being parsed
 * @param is Input source containing the deployment descriptor
 * @param validate true if the XML document needs to be validated against
 * its DTD or schema, false otherwise/*from w w w  . j av a 2  s  . co  m*/
 *
 * @exception JasperException if an I/O or parsing error has occurred
 */
public TreeNode parseXMLDocument(String uri, InputSource is, boolean validate) throws JasperException {

    Document document = null;

    // Perform an XML parse of this document, via JAXP

    // START 6412405
    ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    // END 6412405
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        /* See CR 6399139
        factory.setFeature(
        "http://apache.org/xml/features/validation/dynamic",
        true);
        */
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        builder.setErrorHandler(errorHandler);
        document = builder.parse(is);
        document.setDocumentURI(uri);
        if (validate) {
            Schema schema = getSchema(document);
            if (schema != null) {
                // Validate TLD against specified schema
                schema.newValidator().validate(new DOMSource(document));
            }
            /* See CR 6399139
            else {
            log.warn(Localizer.getMessage(
                "jsp.warning.dtdValidationNotSupported"));
            }
            */
        }
    } catch (ParserConfigurationException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), ex);
    } catch (SAXParseException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml.line", uri,
                Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex);
    } catch (SAXException sx) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), sx);
    } catch (IOException io) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), io);
        // START 6412405
    } finally {
        Thread.currentThread().setContextClassLoader(currentLoader);
        // END 6412405
    }

    // Convert the resulting document to a graph of TreeNodes
    return (convert(null, document.getDocumentElement()));
}

From source file:org.wso2.carbon.apimgt.gateway.mediators.XMLSchemaValidator.java

/**
 * This method validates the request payload xml with the relevant xsd.
 *
 * @param messageContext      This message context contains the request message properties of the relevant
 *                            API which was enabled the XML_Validator message mediation in flow.
 * @param bufferedInputStream Buffered input stream to be validated.
 * @throws APIMThreatAnalyzerException Exception might be occurred while parsing the xml payload.
 *//*from  w ww  . j  a v a  2 s.co  m*/
private boolean validateSchema(MessageContext messageContext, BufferedInputStream bufferedInputStream)
        throws APIMThreatAnalyzerException {
    String xsdURL;
    Schema schema;
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.XSD_URL);
        if (messageProperty == null) {
            return true;
        } else {
            if (String.valueOf(messageProperty).isEmpty()) {
                return true;
            } else {
                xsdURL = String.valueOf(messageProperty);
                URL schemaFile = new URL(xsdURL);
                schema = schemaFactory.newSchema(schemaFile);
                Source xmlFile = new StreamSource(bufferedInputStream);
                Validator validator = schema.newValidator();
                validator.validate(xmlFile);
            }
        }
    } catch (SAXException | IOException e) {
        throw new APIMThreatAnalyzerException("Error occurred while parsing XML payload : " + e);
    }
    return true;
}

From source file:org.wso2.carbon.automation.engine.test.configuration.ConfigurationXSDValidatorTest.java

@Test(groups = "context.unit.test", description = "Upload aar service and verify deployment")
public void validateAutomationXml() throws IOException, SAXException {
    boolean validated = false;
    URL schemaFile = validateXsdFile.toURI().toURL();
    Source xmlFile = new StreamSource(configXmlFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {//w  ww.j  av  a 2 s . c o m
        validator.validate(xmlFile);
        validated = true;

    } catch (SAXException e) {
        log.error(e.getStackTrace());
        throw new SAXException(e);
    }
    Assert.assertTrue(validated);

}

From source file:org.wso2.carbon.governance.generic.util.Util.java

public static Validator getSchemaValidator(String schemaPath) {

    if (serviceSchemaValidator == null) {
        try {/*w ww. j a va  2 s  .c om*/
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new File(schemaPath));
            serviceSchemaValidator = schema.newValidator();
        } catch (SAXException e) {
            log.error("Unable to get a schema validator from the given file path : " + schemaPath);
        }
    }
    return serviceSchemaValidator;
}

From source file:org.wso2.carbon.governance.lcm.util.CommonUtil.java

public static Validator getLifecycleSchemaValidator(String schemaPath) {

    if (lifecycleSchemaValidator == null) {
        try {//from w  ww .  j  a v a2  s. c  o m
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new File(schemaPath));
            lifecycleSchemaValidator = schema.newValidator();
        } catch (SAXException e) {
            log.error("Unable to get a schema validator from the given file path : " + schemaPath);
        }
    }
    return lifecycleSchemaValidator;
}

From source file:org.wso2.carbon.governance.list.util.CommonUtil.java

private static boolean validateRXTContent(String rxtContent, String xsdPath) throws RegistryException {
    try {//  www . ja v  a2s . c  o m
        OMElement rxt = getRXTContentOMElement(rxtContent);
        AXIOMXPath xpath = new AXIOMXPath("//artifactType");
        OMElement c1 = (OMElement) xpath.selectSingleNode(rxt);
        InputStream is = new ByteArrayInputStream(c1.toString().getBytes());
        Source xmlFile = new StreamSource(is);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(xsdPath));
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
    } catch (Exception e) {
        log.error("RXT validation fails due to: " + e.getMessage());
        return false;
    }
    return true;
}