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.apache.stratos.cloud.controller.axiom.AxiomXpathParserUtil.java

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

    Element sourceElement;/*  w  ww .ja  va 2s.c om*/

    // 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 a2 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  . j  a  va 2 s. co  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
 *///from   w w  w  .  j a  v a 2  s  .com
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);/*  w  w  w . j av  a  2  s.co m*/
}

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);//from   w ww  .jav a  2s .  com
}

From source file:org.bungeni.editor.system.ValidateConfiguration.java

public List<SAXParseException> validate(File xmlFile, ConfigInfo config) {
    final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
    try {/* ww  w.j  av a 2 s.  co  m*/
        String pathToXSD = config.getXsdPath();
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new ResourceResolver());
        Schema schema = factory.newSchema(new StreamSource(config.getXsdInputStream()));
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }
        });
        StreamSource streamXML = new StreamSource(xmlFile);
        validator.validate(streamXML);
    } catch (SAXException ex) {
        log.error("Error during validation", ex);
    } catch (IOException ex) {
        log.error("Error during validation", ex);
    } finally {
    }
    return exceptions;
}

From source file:org.cerberus.crud.service.impl.ImportFileService.java

@Override
public AnswerItem importAndValidateXMLFromInputStream(InputStream filecontent, InputStream schemaContent,
        XMLHandlerEnumType handlerType) {
    AnswerItem answer = new AnswerItem();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
    msg.setDescription(//from  w ww  .j  a v  a2s .co m
            msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%OPERATION%", "Import"));
    if (schemaContent != null) {
        try {

            //InputStream data = new BufferedInputStream(filecontent);

            String textContent = IOUtils.toString(filecontent);

            Source source = new StreamSource(IOUtils.toInputStream(textContent));
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            Source sourceschema = new StreamSource(schemaContent);

            Schema schema = factory.newSchema(sourceschema);
            Validator validator = schema.newValidator();
            //is valid
            validator.validate(source);
            //document is valid, then proceed to load the data

            answer.setItem(parseXMLFile(IOUtils.toInputStream(textContent), handlerType));

        } catch (SAXException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_IMPORT_ERROR_FORMAT);
            msg.setDescription(
                    msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%FORMAT%", "XML"));

        } catch (ParserConfigurationException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                    "Unable to parse the XML document. Please try again later."));
        } catch (IOException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                    "Unable to verify if the XML document is valid. Please try again later."));
        }

    }
    answer.setResultMessage(msg);
    return answer;
}

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.endpoint.writer.TestFeatureCollectionMessageBodyWriter.java

@Test
public void testWriteToGeneratesGMLConformantXml() throws IOException, WebApplicationException, SAXException {

    FeatureCollectionMessageBodyWriter wtr = new FeatureCollectionMessageBodyWriter();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    wtr.writeTo(getWfsFeatureCollection(), null, null, null, null, null, stream);
    String actual = stream.toString();

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LSResourceResolver() {

        private Map<String, String> schemaLocations;

        private Map<String, LSInput> inputs;

        {// w ww . j  av a 2  s.c o m
            inputs = new HashMap<String, LSInput>();

            schemaLocations = new HashMap<String, String>();

            schemaLocations.put("xml.xsd", "/w3/1999/xml.xsd");
            schemaLocations.put("xlink.xsd", "/w3/1999/xlink.xsd");
            schemaLocations.put("geometry.xsd", "/gml/2.1.2/geometry.xsd");
            schemaLocations.put("feature.xsd", "/gml/2.1.2/feature.xsd");
            schemaLocations.put("gml.xsd", "/gml/2.1.2/gml.xsd");
            schemaLocations.put("expr.xsd", "/filter/1.0.0/expr.xsd");
            schemaLocations.put("filter.xsd", "/filter/1.0.0/filter.xsd");
            schemaLocations.put("filterCapabilities.xsd", "/filter/1.0.0/filterCapabilties.xsd");
            schemaLocations.put("WFS-capabilities.xsd", "/wfs/1.0.0/WFS-capabilities.xsd");
            schemaLocations.put("OGC-exception.xsd", "/wfs/1.0.0/OGC-exception.xsd");
            schemaLocations.put("WFS-basic.xsd", "/wfs/1.0.0/WFS-basic.xsd");
            schemaLocations.put("WFS-transaction.xsd", "/wfs/1.0.0/WFS-transaction.xsd");
            schemaLocations.put("wfs.xsd", "/wfs/1.0.0/wfs.xsd");
        }

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            String fileName = new java.io.File(systemId).getName();
            if (inputs.containsKey(fileName)) {
                return inputs.get(fileName);
            }

            LSInput input = new DOMInputImpl();
            InputStream is = getClass().getResourceAsStream(schemaLocations.get(fileName));
            input.setByteStream(is);
            input.setBaseURI(baseURI);
            input.setSystemId(systemId);
            inputs.put(fileName, input);
            return input;
        }
    });

    Source wfsSchemaSource = new StreamSource(getClass().getResourceAsStream("/wfs/1.0.0/wfs.xsd"));
    Source testSchemaSource = new StreamSource(getClass().getResourceAsStream("/schema.xsd"));

    Schema schema = schemaFactory.newSchema(new Source[] { wfsSchemaSource, testSchemaSource });

    try {
        schema.newValidator().validate(new StreamSource(new StringReader(actual)));
    } catch (Exception e) {
        fail("Generated GML Response does not conform to WFS Schema" + e.getMessage());
    }
}

From source file:org.commonvox.hbase_column_manager.TestRepositoryAdmin.java

private void validateXmlAgainstXsd(File xmlFile) throws IOException {
    Document hsaDocument = null;/* w  w w  .ja  va 2 s . c  om*/
    Schema hsaSchema = null;
    try {
        hsaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    } catch (ParserConfigurationException pce) {
        fail(TEST_ENVIRONMENT_SETUP_PROBLEM + " parser config exception thrown: " + pce.getMessage());
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " SAX exception thrown while loading test document: "
                + se.getMessage());
    }
    try {
        hsaSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(Paths
                        .get(ClassLoader.getSystemResource(XmlSchemaGenerator.DEFAULT_OUTPUT_FILE_NAME).toURI())
                        .toFile());
    } catch (URISyntaxException ue) {
        fail(TEST_ENVIRONMENT_SETUP_PROBLEM + " URI syntax exception thrown: " + ue.getMessage());
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " SAX exception thrown while loading XML-schema: " + se.getMessage());
    }
    // validate against XSD
    try {
        hsaSchema.newValidator().validate(new DOMSource(hsaDocument));
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " exported HSA file is invalid with respect to " + "XML schema: "
                + se.getMessage());
    }
}