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

From source file:org.kuali.kfs.module.tem.batch.PerDiemXmlInputFileType.java

/**
 * @see org.kuali.kfs.sys.batch.XmlBatchInputFileTypeBase#validateContentsAgainstSchema(java.lang.String, java.io.InputStream)
 *///from   w  w w .  j a v  a  2s  .com
@Override
protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents)
        throws ParseException {

    try {
        // get schemaFile
        UrlResource schemaResource = new UrlResource(schemaLocation);

        // load a WXS schema, represented by a Schema instance
        Source schemaSource = new StreamSource(schemaResource.getInputStream());

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema 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());

        Source source = this.transform(fileContents);
        validator.validate(source);
    } catch (MalformedURLException e2) {
        LOG.error("error getting schema url: " + e2.getMessage());
        throw new RuntimeException("error getting schema url:  " + e2.getMessage(), e2);
    } catch (SAXException e) {
        LOG.error("error encountered while parsing xml " + e.getMessage());
        throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e);
    } catch (IOException e1) {
        LOG.error("error occured while validating file contents: " + e1.getMessage());
        throw new RuntimeException("error occurred while validating file contents: " + e1.getMessage(), e1);
    }
}

From source file:org.kuali.kfs.sys.batch.XmlBatchInputFileTypeBase.java

/**
 * Validates the xml contents against the batch input type schema using the java 1.5 validation package.
 * /* ww  w.  j a va2 s .  c  om*/
 * @param schemaLocation - location of the schema file
 * @param fileContents - xml contents to validate against the schema
 */
protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents)
        throws ParseException {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // get schemaFile
    Resource schemaResource = SpringContext.getResource(schemaLocation);

    // load a WXS schema, represented by a Schema instance
    Source schemaSource = null;
    try {
        schemaSource = new StreamSource(schemaResource.getInputStream());
    } catch (IOException e2) {
        LOG.error("error getting schema stream from url: " + e2.getMessage());
        throw new RuntimeException("error getting schema stream from url:   " + e2.getMessage(), e2);
    }

    Schema schema = null;
    try {
        schema = factory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("error occured while setting schema file: " + e.getMessage());
        throw new RuntimeException("error occured while setting schema file: " + e.getMessage(), e);
    }

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

    // validate
    try {
        validator.validate(new StreamSource(fileContents));
    } catch (SAXException e) {
        LOG.error("error encountered while parsing xml " + e.getMessage());
        throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e);
    } catch (IOException e1) {
        LOG.error("error occured while validating file contents: " + e1.getMessage());
        throw new RuntimeException("error occured while validating file contents: " + e1.getMessage(), e1);
    }
}

From source file:org.kuali.ole.ingest.KrmsXMLSchemaValidator.java

/**
 *  This method return True/False./*from www .ja v a 2  s  .co m*/
 *  This method checks fileContent schema with W3 Xml schema standards,If it matches it return True else return False.
 * @param inputStream
 * @return  boolean
 * @throws org.kuali.ole.exception.ParseException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public boolean validateContentsAgainstSchema(InputStream inputStream)
        throws ParseException, IOException, SAXException {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source schemaSource = null;
        schemaSource = new StreamSource(getFileContents());
        Schema schema = null;
        schema = factory.newSchema(schemaSource);
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new XmlErrorHandler());
        validator.validate(new StreamSource(inputStream));
        return true;
    } catch (Exception ex) {
        //TODO: logging required
    }
    return false;
}

From source file:org.kuali.ole.sys.batch.XmlBatchInputFileTypeBase.java

/**
 * Validates the xml contents against the batch input type schema using the java 1.5 validation package.
 * /*from w ww . ja  va2 s .  c om*/
 * @param schemaLocation - location of the schema file
 * @param fileContents - xml contents to validate against the schema
 */
protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents)
        throws ParseException {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // get schemaFile
    UrlResource schemaResource = null;
    try {
        schemaResource = new UrlResource(schemaLocation);
    } catch (MalformedURLException e2) {
        LOG.error("error getting schema url: " + e2.getMessage());
        throw new RuntimeException("error getting schema url:  " + e2.getMessage(), e2);
    }

    // load a WXS schema, represented by a Schema instance
    Source schemaSource = null;
    try {
        schemaSource = new StreamSource(schemaResource.getInputStream());
    } catch (IOException e2) {
        LOG.error("error getting schema stream from url: " + e2.getMessage());
        throw new RuntimeException("error getting schema stream from url:   " + e2.getMessage(), e2);
    }

    Schema schema = null;
    try {
        schema = factory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("error occured while setting schema file: " + e.getMessage());
        throw new RuntimeException("error occured while setting schema file: " + e.getMessage(), e);
    }

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

    // validate
    try {
        validator.validate(new StreamSource(fileContents));
    } catch (SAXException e) {
        LOG.error("error encountered while parsing xml " + e.getMessage());
        throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e);
    } catch (IOException e1) {
        LOG.error("error occured while validating file contents: " + e1.getMessage());
        throw new RuntimeException("error occured while validating file contents: " + e1.getMessage(), e1);
    }
}

From source file:org.lilyproject.indexer.model.indexerconf.LilyIndexerConfBuilder.java

private void validate(Document document) throws IndexerConfException {
    try {// w  w w . java 2 s. c  o  m
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = getClass().getClassLoader()
                .getResource("org/lilyproject/indexer/model/indexerconf/indexerconf.xsd");
        Schema schema = factory.newSchema(url);
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (Exception e) {
        throw new IndexerConfException("Error validating indexer configuration against XML Schema.", e);
    }
}

From source file:org.lilyproject.indexer.model.indexerconf.LilyIndexerConfBuilder.java

public static void validate(InputStream is) throws IndexerConfException {
    MyErrorHandler errorHandler = new MyErrorHandler();

    try {//from   w ww .j  a v  a 2 s  .com
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = LilyIndexerConfBuilder.class.getClassLoader()
                .getResource("org/lilyproject/indexer/model/indexerconf/indexerconf.xsd");
        Schema schema = factory.newSchema(url);
        Validator validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(new StreamSource(is));
    } catch (Exception e) {
        if (!errorHandler.hasErrors()) {
            throw new IndexerConfException("Error validating indexer configuration.", e);
        } // else it will be reported below
    }

    if (errorHandler.hasErrors()) {
        throw new IndexerConfException("The following errors occurred validating the indexer configuration:\n"
                + errorHandler.getMessage());
    }
}