Example usage for javax.xml.validation SchemaFactory newSchema

List of usage examples for javax.xml.validation SchemaFactory newSchema

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newSchema.

Prototype

public abstract Schema newSchema(Source[] schemas) throws SAXException;

Source Link

Document

Parses the specified source(s) as a schema and returns it as a schema.

Usage

From source file:org.apache.shindig.social.opensocial.util.XSDValidator.java

/**
 * Validate a xml input stream against a supplied schema.
 *
 * @param xml/*from www  . jav a  2  s.c  om*/
 *          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.
 */
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();
        final LSResourceResolver lsr = validator.getResourceResolver();
        validator.setResourceResolver(new LSResourceResolver() {

            public LSInput resolveResource(String arg0, String arg1, String arg2, String arg3, String arg4) {
                log.info("resolveResource(" + arg0 + ',' + arg1 + ',' + arg2 + ',' + arg3 + ',' + arg4 + ')');
                return lsr.resolveResource(arg0, arg1, arg2, arg3, arg4);
            }

        });

        validator.validate(new StreamSource(xml));
    } catch (IOException e) {
    } catch (SAXException e) {
        errors.append(e.getMessage()).append('\n');
    }

    return errors.toString();
}

From source file:org.apache.stratos.adc.mgt.utils.PolicyHolder.java

public void validate(final OMElement omElement, final File schemaFile) throws SAXException, IOException {

    Element sourceElement;//from   w w w .j  a v  a 2  s. c o m

    // if the OMElement is created using DOM implementation use it
    if (omElement instanceof ElementImpl) {
        sourceElement = (Element) omElement;
    } else { // else convert from llom to dom
        sourceElement = getDOMElement(omElement);
    }

    // Create a SchemaFactory capable of understanding WXS schemas.

    // Load a WXS schema, represented by a Schema instance.
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source source = new StreamSource(schemaFile);

    // Create a Validator object, which can be used to validate
    // an instance document.
    Schema schema = factory.newSchema(source);
    Validator validator = schema.newValidator();

    // Validate the DOM tree.
    validator.validate(new DOMSource(sourceElement));
}

From source file:org.apache.stratos.cloud.controller.axiom.AxiomXpathParser.java

public void validate(final OMElement omElement, final File schemaFile) throws Exception {

    Element sourceElement;//from  www  . j  av a  2  s  .c  o  m

    // if the OMElement is created using DOM implementation use it
    if (omElement instanceof ElementImpl) {
        sourceElement = (Element) omElement;
    } else { // else convert from llom to dom
        sourceElement = getDOMElement(omElement);
    }

    // Create a SchemaFactory capable of understanding WXS schemas.

    // Load a WXS schema, represented by a Schema instance.
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source source = new StreamSource(schemaFile);

    // Create a Validator object, which can be used to validate
    // an instance document.
    Schema schema = factory.newSchema(source);
    Validator validator = schema.newValidator();

    // Validate the DOM tree.
    validator.validate(new DOMSource(sourceElement));
}

From source file:org.apache.stratos.cloud.controller.axiom.AxiomXpathParserUtil.java

public static void validate(final OMElement omElement, final File schemaFile) throws SAXException, IOException {

    Element sourceElement;/*from   www  .  j  a  va2 s  .c  o  m*/

    // if the OMElement is created using DOM implementation use it
    if (omElement instanceof ElementImpl) {
        sourceElement = (Element) omElement;
    } else { // else convert from llom to dom
        sourceElement = getDOMElement(omElement);
    }

    // Create a SchemaFactory capable of understanding WXS schemas.

    // Load a WXS schema, represented by a Schema instance.
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source source = new StreamSource(schemaFile);

    // Create a Validator object, which can be used to validate
    // an instance document.
    Schema schema = factory.newSchema(source);
    Validator validator = schema.newValidator();

    // Validate the DOM tree.
    validator.validate(new DOMSource(sourceElement));
}

From source file:org.apache.stratos.manager.utils.PolicyHolder.java

public void validate(final OMElement omElement, final File schemaFile) throws SAXException, IOException {

    Element sourceElement;//from   w w  w .  j  a v a 2  s .co  m

    // if the OMElement is created using DOM implementation use it
    if (omElement instanceof ElementImpl) {
        sourceElement = (Element) omElement;
    } else { // else convert from llom to dom
        sourceElement = getDOMElement(omElement);
    }

    // Create a SchemaFactory capable of understanding WXS schemas.

    // Load a WXS schema, represented by a Schema subscription.
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source source = new StreamSource(schemaFile);

    // Create a Validator object, which can be used to validate
    // an subscription document.
    Schema schema = factory.newSchema(source);
    Validator validator = schema.newValidator();

    // Validate the DOM tree.
    validator.validate(new DOMSource(sourceElement));
}

From source file:org.apache.synapse.format.syslog.SyslogMessageBuilderTest.java

private SyslogMessage test(String message) throws Exception {
    MessageContext msgContext = new MessageContext();
    ByteArrayInputStream in = new ByteArrayInputStream(message.getBytes("us-ascii"));
    OMElement element = new SyslogMessageBuilder().processDocument(in, null, msgContext);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(
            new StreamSource(SyslogMessageBuilderTest.class.getResource("schema.xsd").toExternalForm()));
    Validator validator = schema.newValidator();
    validator.setErrorHandler(new ErrorHandler() {
        public void error(SAXParseException exception) throws SAXException {
            throw exception;
        }/*  w  ww  .  jav a 2  s .c o  m*/

        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }

        public void warning(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });
    validator.validate(new OMSource(element));
    String pidString = element.getAttributeValue(new QName(SyslogConstants.PID));
    return new SyslogMessage(element.getAttributeValue(new QName(SyslogConstants.FACILITY)),
            element.getAttributeValue(new QName(SyslogConstants.SEVERITY)),
            element.getAttributeValue(new QName(SyslogConstants.TAG)),
            pidString == null ? -1 : Integer.parseInt(pidString), element.getText());
}

From source file:org.apache.synapse.mediators.validate.ValidateMediator.java

/**
 * Perform actual initialization of this validate mediator instance - if required
 *//*  w  w w  .ja v a  2  s  . c  o m*/
private void initialize(MessageContext msgCtx) {

    // flag to check if we need to initialize/re-initialize the schema Validator
    boolean reCreate = false;

    // if any of the schemas are not loaded or expired, load or re-load them
    Iterator iter = schemaKeys.iterator();
    while (iter.hasNext()) {
        String propKey = (String) iter.next();
        Property dp = msgCtx.getConfiguration().getPropertyObject(propKey);
        if (dp != null && dp.isDynamic()) {
            if (!dp.isCached() || dp.isExpired()) {
                reCreate = true; // request re-initialization of Validator
            }
        }
    }

    // do not re-initialize Validator unless required
    if (!reCreate && validator != null) {
        return;
    }

    try {
        // Create SchemaFactory and configure for the default schema language - XMLSchema
        SchemaFactory factory = SchemaFactory.newInstance(DEFAULT_SCHEMA_LANGUAGE);
        factory.setErrorHandler(errorHandler);

        // set any features on/off as requested
        iter = properties.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String value = (String) entry.getValue();
            factory.setFeature((String) entry.getKey(), value != null && "true".equals(value));
        }

        Schema schema = null;

        StreamSource[] sources = new StreamSource[schemaKeys.size()];
        iter = schemaKeys.iterator();
        int i = 0;
        while (iter.hasNext()) {
            String propName = (String) iter.next();
            sources[i++] = Util.getStreamSource(msgCtx.getConfiguration().getProperty(propName));
        }
        schema = factory.newSchema(sources);

        // Setup validator and input source
        // Features set for the SchemaFactory get propagated to Schema and Validator (JAXP 1.4)
        validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);

    } catch (SAXException e) {
        handleException("Error creating Validator", e);
    }
}

From source file:org.apache.tinkerpop.gremlin.structure.io.IoTest.java

private static void validateXmlAgainstGraphMLXsd(final File file) throws Exception {
    final Source xmlFile = new StreamSource(file);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(IoTest.class.getResource(
            TestHelper.convertPackageToResourcePath(GraphMLResourceAccess.class) + "graphml-1.1.xsd"));
    final Validator validator = schema.newValidator();
    validator.validate(xmlFile);/*from   w w w.  j  av a  2 s .c  om*/
}

From source file:org.apache.tinkerpop.gremlin.structure.IoTest.java

private void validateXmlAgainstGraphMLXsd(final File file) throws Exception {
    final Source xmlFile = new StreamSource(file);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory
            .newSchema(IoTest.class.getResource(GRAPHML_RESOURCE_PATH_PREFIX + "graphml-1.1.xsd"));
    final Validator validator = schema.newValidator();
    validator.validate(xmlFile);//  w w  w  . j a  v a 2s  . c  om
}

From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java

public static Schema loadXMLSecuritySchemas() throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LSResourceResolver() {
        @Override//  w w w.jav  a  2 s .  c  om
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            if ("http://www.w3.org/2001/XMLSchema.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/XMLSchema.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("XMLSchema.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/XMLSchema.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("datatypes.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/datatypes.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd"
                    .equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils.getResourceAsStream(
                        "bindings/schemas/xmldsig-core-schema.xsd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xml.xsd",
                        XMLSecurityConstants.class));
                return concreteLSInput;
            }
            return null;
        }
    });
    Schema schema = schemaFactory.newSchema(new Source[] {
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/exc-c14n.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xmldsig-core-schema.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema-11.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xmldsig11-schema.xsd",
                    XMLSecurityConstants.class)), });
    return schema;
}