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:io.fabric8.camel.tooling.util.CamelNamespaces.java

private static void loadSchemas(SchemaFinder loader) throws SAXException, IOException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    XsdDetails[] xsds = new XsdDetails[] {
            new XsdDetails("camel-spring.xsd", "http://camel.apache.org/schema/spring/camel-spring.xsd",
                    CamelEndpointFactoryBean.class),
            new XsdDetails("camel-blueprint.xsd",
                    "http://camel.apache.org/schema/blueprint/camel-blueprint.xsd",
                    org.apache.camel.blueprint.CamelEndpointFactoryBean.class) };

    List<Source> sources = new ArrayList<Source>(xsds.length);

    for (XsdDetails xsdd : xsds) {
        URL url = loader.findSchema(xsdd);
        if (url != null) {
            sources.add(new StreamSource(url.openStream(), xsdd.getUri()));
        } else {// ww  w .  j a v a 2  s .  c o m
            System.out.println("Warning could not find local resource " + xsdd.getPath() + " on classpath");
            sources.add(new StreamSource(xsdd.getUri()));
        }
    }

    _schema = factory.newSchema(sources.toArray(new Source[sources.size()]));
}

From source file:cz.strmik.cmmitool.cmmi.DefaultRatingScalesProvider.java

private void validateScalesDocument(Document document) throws SAXException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source schemaFile = new StreamSource(getClass().getClassLoader().getResourceAsStream(SCALES_XSD));
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(document));
}

From source file:eu.planets_project.tb.gui.backing.exp.utils.ExpTypeWeeUtils.java

private void checkValidXMLConfig(InputStream xmlWFConfig) throws Exception {
    InputStream bis = getClass().getClassLoader().getResourceAsStream("planets_wdt.xsd");
    try {/*from  w  w  w .j av a2  s  . c o  m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(bis));
        Validator validator = schema.newValidator();
        // Validate file against schema
        XMLOutputter outputter = new XMLOutputter();
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(xmlWFConfig);
        validator.validate(new StreamSource(new StringReader(outputter.outputString(doc.getRootElement()))));
    } catch (Exception e) {
        String err = "The provided xmlWFConfig is not valid against the currently used planets_wdt_xsd schema";
        log.debug(err, e);
        throw new Exception(err, e);
    } finally {
        bis.close();
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.util.QCliveXMLSchemaValidator.java

protected Boolean validateSchema(final List<Source> schemaSourceList, final Document document,
        final File xmlFile, final QcContext context) throws SAXException, IOException {

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // instantiate the schema
    Schema schema = factory.newSchema(schemaSourceList.toArray(new Source[] {}));
    // now validate the file against the schema
    // note: supposedly there is a way to just let the XML document figure
    // out its own schema based on what is referred to, but
    // I could not get that to work, which is why I am looking for the
    // schema in the attribute

    final DOMSource source = new DOMSource(document);
    final Validator validator = schema.newValidator();

    // wow this looks dumb, but isValid has to be final to be accessed from
    // within an inner class
    // and this was IDEA's solution to the problem: make it an array and set
    // the first element of the array
    final boolean[] isValid = new boolean[] { true };

    // add error handler that will add validation errors and warnings
    // directly to the QcContext object
    validator.setErrorHandler(new ErrorHandler() {
        public void warning(final SAXParseException exception) {
            context.addWarning(new StringBuilder().append(xmlFile.getName()).append(": ")
                    .append(exception.getMessage()).toString());
        }//from  ww  w. j  a  v a2  s  .c o  m

        public void error(final SAXParseException exception) {
            context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR,
                    xmlFile.getName(), new StringBuilder().append(xmlFile.getName()).append(": ")
                            .append(exception.getMessage()).toString()));
            isValid[0] = false;
        }

        public void fatalError(final SAXParseException exception) throws SAXException {
            context.getArchive().setDeployStatus(Archive.STATUS_INVALID);
            throw exception;
        }
    });
    validator.validate(source);
    return isValid[0];
}

From source file:io.aino.agents.core.config.InputStreamConfigBuilder.java

/**
 * Validates the config file against XSD schema.
 *
 * @param stream InputStream to config file.
 *//*w w w.  ja v a  2 s. co  m*/
private void validateSchema(InputStream stream) {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        InputStream xsdStream = this.getClass().getClassLoader().getResourceAsStream(LOGGER_SCHEMA);
        Schema schema = factory.newSchema(new StreamSource(xsdStream));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(stream));
    } catch (SAXException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    } catch (IOException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    }
}

From source file:be.fedict.eid.dss.model.bean.XmlSchemaManagerBean.java

public void add(String revision, InputStream xsdInputStream)
        throws InvalidXmlSchemaException, ExistingXmlSchemaException {
    byte[] xsd;//from   w w  w .  j  a  v a2s .  c  o m
    try {
        xsd = IOUtils.toByteArray(xsdInputStream);
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
    ByteArrayInputStream schemaInputStream = new ByteArrayInputStream(xsd);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.entityManager));
    StreamSource schemaSource = new StreamSource(schemaInputStream);
    try {
        schemaFactory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("SAX error: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException("SAX error: " + e.getMessage(), e);
    } catch (RuntimeException e) {
        LOG.error("Runtime exception: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException(e.getMessage(), e);
    }

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    schemaInputStream = new ByteArrayInputStream(xsd);
    Document schemaDocument;
    try {
        schemaDocument = documentBuilder.parse(schemaInputStream);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    String namespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");
    LOG.debug("namespace: " + namespace);

    XmlSchemaEntity existingXmlSchemaEntity = this.entityManager.find(XmlSchemaEntity.class, namespace);
    if (null != existingXmlSchemaEntity) {
        throw new ExistingXmlSchemaException();
    }

    XmlSchemaEntity xmlSchemaEntity = new XmlSchemaEntity(namespace, revision, xsd);
    this.entityManager.persist(xmlSchemaEntity);
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * @throws IOException//from   w ww .  j a v a2  s  .  c om
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private static void initializeSchemas() throws IOException, SAXException, ParserConfigurationException {
    File[] schemaFiles = ResourceUtil.getFilenamesInDirectory("xsd/", TestBase.class.getClassLoader());
    schemas = new HashMap<String, Schema>();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (File file : schemaFiles) {
        try {
            Schema schema = sf.newSchema(file);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                private String nameSpace = null;
                private boolean found = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if (!found) {
                        String tagName = null;
                        int ix = qName.indexOf(":");
                        if (ix >= 0) {
                            tagName = qName.substring(ix + 1);
                        } else {
                            tagName = qName;
                        }
                        if ("schema".equals(tagName)) {
                            nameSpace = attributes.getValue("targetNamespace");
                            found = true;
                        }
                    }
                }

                public String toString() {
                    return nameSpace;
                }
            };
            parser.parse(file, handler);
            if (handler.toString() != null) {
                schemas.put(handler.toString(), schema);
            } else {
                logger.warn("Error reading xml schema: " + file);
            }

        } catch (Exception e) {
            logger.warn("Invalid xml schema " + file);
            logger.debug("Stacktrace: ", e);
        }

    }
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SOAPMessageValidatorInterceptor.java

private List<Validator> getValidators() throws Exception {
    log.info("Get validators for WSDL: " + wsdl);
    WSDLParserContext ctx = new WSDLParserContext();
    ctx.setInput(wsdl);/*from  w w w  .j  a  va  2  s  .co m*/
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    sf.setResourceResolver(new SOAModelResourceResolver(wsdl));
    List<Validator> validators = new ArrayList<Validator>();
    for (Schema schema : getEmbeddedSchemas(ctx)) {
        log.info("Adding embedded schema: " + schema);
        Validator validator = sf
                .newSchema(new StreamSource(new ByteArrayInputStream(schema.getAsString().getBytes())))
                .newValidator();
        validator.setErrorHandler(new SchemaValidatorErrorHandler());
        validators.add(validator);
    }
    return validators;
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Validate the configuration against XML Schema.
 *
 * @throws ConfigException if not valid/* w  w w . j  av a 2  s .c  o  m*/
 */
private void validateXMLConfiguration(InputStream xmlConfigurationStream) throws IOException, ConfigException {
    assert xmlConfigurationStream != null;
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        final Schema schema = sf
                .newSchema(MathMLCanonicalizer.class.getResource(Settings.getProperty("configSchema")));

        final Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlConfigurationStream));
    } catch (SAXException ex) {
        throw new ConfigException("configuration not valid\n" + ex.getMessage(), ex);
    }
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.XMLSchemaValidator.java

@Override
protected List<Validator> createValidators() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    sf.setResourceResolver(resourceResolver.toLSResourceResolver());
    List<Validator> validators = new ArrayList<Validator>();
    log.debug("Creating validator for schema: " + location);
    StreamSource ss = new StreamSource(resourceResolver.resolve(location));
    ss.setSystemId(location);/*w  w  w . j  ava 2  s . com*/
    Validator validator = sf.newSchema(ss).newValidator();
    validator.setResourceResolver(resourceResolver.toLSResourceResolver());
    validator.setErrorHandler(new SchemaValidatorErrorHandler());
    validators.add(validator);
    return validators;
}