Example usage for javax.xml.validation SchemaFactory newInstance

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

Introduction

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

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

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
 *///from   w w w .java  2  s  .c  om
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 w w.ja va 2  s .co  m*/
 * @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.//from   w w w .  ja  v a 2s. c  o  m
 * <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.
 * //from  w  w  w  .  j ava  2  s  .  c  om
 * @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();//from 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  .ja  v a 2 s  .  co m*/

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

From source file:org.jts.eclipse.ui.actions.importbinding.Util.java

/**
  * Filter jsidl files, unmarshal and place in a Map.
  * @param fileList list of JSIDL XML files containing service sets
  * @return A Map from service set ID/version strings to JAXB instances representing those service sets.
 * @throws JAXBException /*from w  w w  . j  av  a2s . c o  m*/
 * @throws SAXException 
  */
public static Map getObjectMapFromFile(List<File> fileList, List<ServiceDef> tmp)
        throws JAXBException, SAXException {
    Map objMap = new HashMap();
    Document doc = null;
    DocumentBuilder db = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Unmarshaller um = null;

    // Set up the unmarshaller with the schema included with the code
    // generator.
    try {
        JAXBContext jc = JAXBContext.newInstance("org.jts.jsidl.binding");
        um = jc.createUnmarshaller();
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Bundle bundle = CjsidlActivator.getInstance().getBundle();
        String schema_loc;
        if (new File(SCHEMA_PATH).exists()) {
            schema_loc = SCHEMA_PATH;
        } else if (new File(JTS_SCHEMA_PATH).exists()) {
            schema_loc = JTS_SCHEMA_PATH;
        } else if (new File(DEPLOYED_SCHEMA_PATH).exists()) {
            schema_loc = DEPLOYED_SCHEMA_PATH;
        } else {
            throw new Exception("Unable to find the schema path for jsidl_plus.xsd: "
                    + (new File(SCHEMA_PATH).getAbsolutePath()) + "\n\t"
                    + (new File(JTS_SCHEMA_PATH).getAbsolutePath()) + "\n\t"
                    + (new File(DEPLOYED_SCHEMA_PATH).getAbsolutePath()));
        }
        //         IPath path = new Path(schema_loc);
        //         URL schemaUrl = FileLocator.find(bundle, path,
        //               Collections.EMPTY_MAP);
        //         File schemaFile = new File(FileLocator.toFileURL(schemaUrl).toURI());
        File schemaFile = new File(schema_loc);
        Schema schema = sf.newSchema(schemaFile);
        um.setSchema(schema);

        // Try parsing each file.

        db = dbf.newDocumentBuilder();

        for (int ii = 0; ii < fileList.size(); ii++) {
            File file = fileList.get(ii);
            final String fileName = file.toString();

            doc = db.parse(file);

            Element root = doc.getDocumentElement();

            if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0")) {

                Object o = um.unmarshal(file);
                objMap.put(root.getAttribute("id") + "-" + root.getAttribute("version"), o);
                if (o instanceof ServiceDef) {
                    tmp.add((ServiceDef) o);
                }

            }
        }
    } catch (JAXBException jaxbe) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, jaxbe.getMessage(), jaxbe);
        throw jaxbe;
    } catch (SAXException saxe) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, saxe.getMessage(), saxe);
        throw saxe;
    } catch (URISyntaxException e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return objMap;
}

From source file:org.jts.gui.importJSIDL.Import.java

public Import() {
    try {//www .j a v a  2 s  .c  o m
        if (um == null) {
            JAXBContext jc = JAXBContext.newInstance("org.jts.jsidl.binding");
            um = jc.createUnmarshaller();
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(sourceSchema));
            um.setSchema(schema);
        }
    } catch (JAXBException jaxbe) {
        throw new GUIError(jaxbe.getCause());
    } catch (SAXException saxe) {
        throw new GUIError(saxe.getCause());
    }
}

From source file:org.kepler.kar.karxml.KarXml.java

/**
 * Validate the document against the schema. Currently we only validate against
 * kar xml 2.0.0 and 2.1.0. If it is not a kar xml 2.0.0 or 2.1.0 xml, this method will return true.
 * @param document  the document need to be validate
 * @return true if it is a valid document
 *//*from ww w.j  av  a 2  s.com*/
public static boolean validateDocument(Document document) {
    if (document == null) {
        return false;
    }
    try {
        Node docElement = document.getDocumentElement();
        String nameSpace = docElement.getNamespaceURI();
        log.debug("The name space is ===== " + nameSpace);

        if (nameSpace == null || !nameSpace.equals(KARFile.KAR_VERSION_200_NAMESPACE_DEFAULT)
                || !nameSpace.equals(KARFile.KAR_VERSION_210_NAMESPACE_DEFAULT)) {
            return true;
        }
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        String resourceDir = KARFile.getResourceDir(nameSpace);
        String resourceFileName = KARFile.getResourceFileName(nameSpace);
        // ClassLoader.getResource javadoc says: 
        // The name of a resource is a '/'-separated path name that identifies the resource.
        // so I am using a hardcode / in this path:
        Source schemaFile = new StreamSource(
                KarXml.class.getClassLoader().getResourceAsStream(resourceDir + "/" + resourceFileName));
        Schema schema = factory.newSchema(schemaFile);
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (SAXException ex) {
        ex.printStackTrace();
        return false;
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }
    log.debug("return true");
    return true;
}

From source file:org.kuali.kfs.module.ar.batch.CustomerLoadXMLSchemaTest.java

/**
 * Validates the xml contents against the batch input type schema using the java 1.5 validation package.
 * //w  ww. j a  va  2 s . c  o m
 * @param schemaLocation - location of the schema file
 * @param fileContents - xml contents to validate against the schema
 */
private void validateContentsAgainstSchema(InputStream schemaLocation, InputStream fileContents)
        throws ParseException, MalformedURLException, IOException, SAXException {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // load a WXS schema, represented by a Schema instance
    Source schemaSource = null;
    schemaSource = new StreamSource(schemaLocation);

    Schema schema = null;
    schema = factory.newSchema(schemaSource);

    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    validator.setErrorHandler(new XmlErrorHandler());

    // validate
    validator.validate(new StreamSource(fileContents));
}