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.flowable.cmmn.converter.CmmnXmlConverter.java

protected Schema createSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;//from   w  w w .j a v  a2  s .com
    if (classloader != null) {
        schema = factory.newSchema(classloader.getResource(XSD_LOCATION));
    }

    if (schema == null) {
        schema = factory.newSchema(this.getClass().getClassLoader().getResource(XSD_LOCATION));
    }

    if (schema == null) {
        throw new CmmnXMLException("CMND XSD could not be found");
    }
    return schema;
}

From source file:org.forgerock.maven.plugins.LinkTester.java

@Override()
public void execute() throws MojoExecutionException, MojoFailureException {
    if (outputFile != null) {
        if (!outputFile.isAbsolute()) {
            outputFile = new File(project.getBasedir(), outputFile.getPath());
        }/*from ww w.j  av a  2  s. co  m*/
        if (outputFile.exists()) {
            debug("Deleting existing outputFile: " + outputFile);
            outputFile.delete();
        }
        try {
            outputFile.createNewFile();
            fileWriter = new FileWriter(outputFile);
        } catch (IOException ioe) {
            error("Error while creating output file", ioe);
        }
    }
    initializeSkipUrlPatterns();

    //Initialize XML parsers and XPath expressions
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setExpandEntityReferences(false);
    dbf.setXIncludeAware(xIncludeAware);

    if (validating) {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = sf.newSchema(new URL(DOCBOOK_XSD));
            dbf.setSchema(schema);
        } catch (MalformedURLException murle) {
            error("Invalid URL provided as schema source", murle);
        } catch (SAXException saxe) {
            error("Parsing error occurred while constructing schema for validation", saxe);
        }
    }
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        db.setErrorHandler(new LoggingErrorHandler(this));
    } catch (ParserConfigurationException pce) {
        throw new MojoExecutionException("Unable to create new DocumentBuilder", pce);
    }

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new XmlNamespaceContext());
    XPathExpression expr;
    try {
        expr = xpath.compile("//@xml:id");
    } catch (XPathExpressionException xpee) {
        throw new MojoExecutionException("Unable to compile Xpath expression", xpee);
    }

    if (docSources != null) {
        for (DocSource docSource : docSources) {
            processDocSource(docSource, db, expr);
        }
    }

    try {
        if (!skipOlinks) {
            //we can only check olinks after going through all the documents, otherwise we would see false
            //positives, because of the not yet processed files
            for (Map.Entry<String, Collection<String>> entry : (Set<Map.Entry<String, Collection<String>>>) olinks
                    .entrySet()) {
                for (String val : entry.getValue()) {
                    checkOlink(entry.getKey(), val);
                }
            }
        }
        if (!failedUrls.isEmpty()) {
            error("The following files had invalid URLs:\n" + failedUrls.toString());
        }
        if (!timedOutUrls.isEmpty()) {
            warn("The following files had unavailable URLs (connection or read timed out):\n"
                    + timedOutUrls.toString());
        }
        if (failedUrls.isEmpty() && timedOutUrls.isEmpty() && !failure) {
            //there are no failed URLs and the parser didn't encounter any errors either
            info("DocBook links successfully tested, no errors reported.");
        }
    } finally {
        flushReport();
    }
    if (failOnError) {
        if (failure || !failedUrls.isEmpty()) {
            throw new MojoFailureException("One or more error occurred during plugin execution");
        }
    }
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

protected void checkValidationErorrs(Document dom, String schemaLocation) throws SAXException, IOException {
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new File(schemaLocation));
    checkValidationErrors(dom, schema);//www. jav  a 2 s . c  o m
}

From source file:org.icefaces.application.showcase.view.builder.ApplicationBuilder.java

public void loadMetaData() {

    try {/*w  w  w .java2 s .  c om*/
        // create a jab context
        JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_FACTORY_PACKAGE);

        // schema factory for data validation purposes
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(
                new StreamSource(getResourceStream(META_DATA_RESOURCE_PATH + "/" + SCHEMA_FILE_NAME)));

        // create an unmarshaller and set schema
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);

        // grab and assign the application object graph
        application = (Application) unmarshaller.unmarshal(
                new StreamSource(getResourceStream(META_DATA_RESOURCE_PATH + "/" + META_DATA_FILE_NAME)));

    } catch (JAXBException e) {
        logger.error("JAXB Exception during unmarshalling:", e);
        throw new IllegalStateException("Could not load/unmarshal Application Meta Data: ", e);
    } catch (SAXException e) {
        logger.error("SAX Exception during unmarshalling:", e);
        throw new IllegalStateException("Could not load/unmarshal Application Meta Data: ", e);
    }

}

From source file:org.impalaframework.util.XMLDomUtils.java

/**
 * Validates document of given description using w3c.org schema validation
 * @param document the DOM document instance
 * @param description a description of the document, typically name or path
 * @param xsdResource the schema resource used for validation
 *//*  ww w.  j av  a 2s . com*/
public static void validateDocument(Document document, String description, Resource xsdResource) {

    Assert.notNull(xsdResource, "xsdResource cannot be null");

    if (!xsdResource.exists()) {
        throw new ExecutionException(
                "Cannot validate document as xsdResource '" + xsdResource + "' does not exist");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Validating using schema resource " + xsdResource.getDescription());
        }
    }

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    try {
        InputStream inputStream = xsdResource.getInputStream();
        Source source = new StreamSource(inputStream);

        Schema schema = factory.newSchema(source);
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (SAXParseException e) {
        throw new ExecutionException("Error on " + e.getLineNumber() + ", column " + e.getColumnNumber()
                + " in " + description + ": " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new ExecutionException("Error parsing " + description + ": " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.infoscoop.api.rest.v1.controller.admin.TabLayoutsController.java

/**
 * validatation and parse XMLString for tabLayouts.
 * @param xml//from  w  ww .  ja  v  a  2s .com
 * @return
 */
private Document parseTabLayoutsXML(String xml) {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL path = Thread.currentThread().getContextClassLoader().getResource("tabLayouts.xsd");
        File f = new File(path.toURI());
        Schema schema = factory.newSchema(f);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setSchema(schema);
        dbf.setNamespaceAware(true);

        DocumentBuilder parser = dbf.newDocumentBuilder();
        Document doc = parser.parse(new InputSource(new StringReader(xml)));

        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(doc));

        return doc;
    } catch (SAXException e) {
        // instance document is invalid
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.intermine.install.project.source.SourceInfoLoader.java

/**
 * Initialise this object by creating the JAXB context and the XML validation
 * schema for loading source descriptors, then loading each available data source
 * metadata.// w  w w  .j av  a  2s  . c  om
 * <p>This method should be called exactly once at application start up.</p>
 * 
 * @throws JAXBException if there is a problem preparing the JAXB system, or
 * reading any of the source descriptors.
 * @throws IOException if there is an I/O error while loading the configuration.
 * @throws IllegalStateException if this object has already been initialised.
 */
public synchronized void initialise() throws JAXBException, IOException {
    if (initialised) {
        throw new IllegalStateException("SourceInfoLoader already initialised");
    }

    SchemaFactory sfact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        schema = sfact.newSchema(new StreamSource(getClass().getResourceAsStream("/xsd/sourcedescriptor.xsd")));
    } catch (SAXException e) {
        throw new JAXBException("Could not parse sourcedescriptor.xsd", e);
    }
    jaxbContext = JAXBContext.newInstance("org.intermine.install.project.source");

    // Initialise known types list.

    knownTypes = new ArrayList<String>();

    String resourceName = RESOURCE_PATH + "sourcetypes.txt";
    InputStream in = getClass().getResourceAsStream(resourceName);
    if (in == null) {
        throw new FileNotFoundException(resourceName);
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            knownTypes.add(line.trim());
        }
    } finally {
        in.close();
    }

    knownTypes = Collections.unmodifiableList(knownTypes);

    // Initialise information for these known types. 

    for (String type : knownTypes) {
        String descriptorFile = RESOURCE_PATH + type + ".xml";
        InputStream descriptorStream = getClass().getResourceAsStream(descriptorFile);
        if (descriptorStream == null) {
            logger.warn("There is no source descriptor file for the type " + type);
            continue;
        }

        // Load the source descriptor.
        SourceDescriptor source;
        try {
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            unmarshaller.setSchema(schema);
            JAXBElement<?> result = (JAXBElement<?>) unmarshaller.unmarshal(descriptorStream);
            source = (SourceDescriptor) result.getValue();
        } finally {
            descriptorStream.close();
        }

        // Load default property values, if any are present.
        Properties defaults = new Properties();
        String defaultsFile = RESOURCE_PATH + type + "_defaults.properties";
        InputStream defaultsStream = getClass().getResourceAsStream(defaultsFile);
        if (defaultsStream != null) {
            try {
                defaults.load(defaultsStream);
            } finally {
                defaultsStream.close();
            }
        }

        SourceInfo info = new SourceInfo(type, source, defaults);
        knownSources.put(type, info);

        if (info.getSource().getDerivation() != null) {
            derivatedSources.put(info.getSource().getDerivation().getAntTask(), info);
        }
    }

    initialised = true;
}

From source file:org.intermine.modelviewer.jaxb.ConfigParser.java

/**
 * Initialise this parser, setting up the JAXB contexts, validation schemas,
 * XML namespaces and relative schema locations.
 * /*  w ww . ja va  2 s  .  c  o  m*/
 * @throws JAXBException if there is a problem initialising the JAXB system.
 * @throws SAXException if there is a problem initialising the SAX system.
 */
public ConfigParser() throws JAXBException, SAXException {

    parserFactory = SAXParserFactory.newInstance();
    parserFactory.setNamespaceAware(true);
    parserFactory.setValidating(true);

    // Get local versions of the schemas that are included in the JAR.

    URL genomicCoreUrl = getClass().getResource("/xsd/genomic-core.xsd");
    if (genomicCoreUrl == null) {
        throw new SAXException("Cannot locate schema /xsd/genomic-core.xsd on class path.");
    }
    URL coreUrl = getClass().getResource("/xsd/core.xsd");
    if (coreUrl == null) {
        throw new SAXException("Cannot locate schema /xsd/core.xsd on class path.");
    }
    URL genomicUrl = getClass().getResource("/xsd/genomic.xsd");
    if (genomicUrl == null) {
        throw new SAXException("Cannot locate schema /xsd/genomic.xsd on class path.");
    }
    URL projectUrl = getClass().getResource("/xsd/project.xsd");
    if (projectUrl == null) {
        throw new SAXException("Cannot locate schema /xsd/project.xsd on class path.");
    }

    // Set up the XML validation (javax.xml.validation) schemas.

    SchemaFactory sfact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemas.put(Context.CORE,
            sfact.newSchema(new Source[] { new SAXSource(new InputSource(genomicCoreUrl.toExternalForm())),
                    new SAXSource(new InputSource(coreUrl.toExternalForm())) }));
    schemas.put(Context.GENOMIC,
            sfact.newSchema(new Source[] { new SAXSource(new InputSource(genomicCoreUrl.toExternalForm())),
                    new SAXSource(new InputSource(genomicUrl.toExternalForm())) }));
    schemas.put(Context.PROJECT, sfact.newSchema(new SAXSource(new InputSource(projectUrl.toExternalForm()))));

    namespaces.put(Context.CORE, CORE_NAMESPACE);
    namespaces.put(Context.GENOMIC, GENOMIC_NAMESPACE);
    namespaces.put(Context.PROJECT, PROJECT_NAMESPACE);

    xsdUrls.put(Context.CORE, CORE_URL);
    xsdUrls.put(Context.GENOMIC, GENOMIC_URL);
    xsdUrls.put(Context.PROJECT, PROJECT_URL);

    // Fetch and store the JAXB contexts for each type of XML document.

    jaxbContexts.put(Context.GENOMIC, JAXBContext.newInstance("org.intermine.modelviewer.genomic"));
    jaxbContexts.put(Context.CORE, jaxbContexts.get(Context.GENOMIC));
    //jaxbContexts.put(Context.CORE,
    //        JAXBContext.newInstance("org.intermine.modelviewer.core"));
    jaxbContexts.put(Context.PROJECT, JAXBContext.newInstance("org.intermine.modelviewer.project"));
}

From source file:org.jboss.cdi.tck.test.shrinkwrap.descriptors.ejb.EjbJarDescriptorBuilderTest.java

@Test
public void testDescriptorIsValid()
        throws ParserConfigurationException, SAXException, DescriptorExportException, IOException {

    EjbJarDescriptor ejbJarDescriptor = new EjbJarDescriptorBuilder().messageDrivenBeans(
            newMessageDriven("TestQueue", QueueMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Queue")
                    .addActivationConfigProperty("destinationLookup", "test_queue"),
            newMessageDriven("TestTopic", TopicMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Topic")
                    .addActivationConfigProperty("destinationLookup", "test_topic"))
            .build();/*w w  w.  j a  v  a 2  s  .  com*/

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

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            try {
                if (systemId.startsWith("http")) {
                    // Ugly workaround for xml.xsd
                    systemId = StringUtils.substringAfterLast(systemId, "/");
                }
                return new Input(publicId, systemId,
                        new FileInputStream(new File("src/test/resources/xsd", systemId)));
            } catch (FileNotFoundException e) {
                throw new IllegalStateException();
            }
        }
    });
    schemaFactory.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
        }

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

        @Override
        public void error(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });

    Source schemaFile = new StreamSource(
            new FileInputStream(new File("src/test/resources/xsd", "ejb-jar_3_1.xsd")));
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator
            .validate(new StreamSource(new ByteArrayInputStream(ejbJarDescriptor.exportAsString().getBytes())));
}

From source file:org.jdal.xml.Main.java

public static void validateXML(String xmlPath, String schemaPath) throws SAXException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new File(schemaPath));
    ValidationResult vr = XMLUtils.validateSchema(FileUtils.readFileToString(new File(xmlPath), "UTF-8"),
            schema);// www. j a  v a  2s. c  o  m

    String result = vr.isValid() ? "Valid" : "Invalid\n";
    System.out.println(result + vr.getMessage());
}