List of usage examples for javax.xml.validation SchemaFactory newSchema
public abstract Schema newSchema(Source[] schemas) throws SAXException;
From source file:com.silverpeas.importExport.control.ImportExport.java
/** * Mthode retournant l'arbre des objets mapps sur le fichier xml pass en paramtre. * * @param xmlFileName le fichier xml interprt par Castor * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML Castor * @throws ImportExportException/* w w w . j av a2s .co m*/ */ SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException { SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_ENTER_METHOD", "xmlFileName = " + xmlFileName); try { InputSource xmlInputSource = new InputSource(xmlFileName); String xsdPublicId = settings.getString("xsdPublicId"); String xsdSystemId = settings.getString("xsdDefaultSystemId"); // Load and parse default XML schema for import/export SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema", "com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory", null); Schema schema = schemaFactory.newSchema(new StreamSource(xsdSystemId)); // Create an XML parser for loading XML import file SAXParserFactory factory = SAXParserFactory .newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null); factory.setValidating(false); factory.setNamespaceAware(true); factory.setSchema(schema); SAXParser parser = factory.newSAXParser(); // First try to determine to load the XML file using the default // XML-Schema ImportExportErrorHandler errorHandler = new ImportExportErrorHandler(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(errorHandler); try { xmlReader.parse(xmlInputSource); } catch (SAXException ex) { SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("XML File ")).append(xmlFileName) .append(" is not valid according to default schema").toString()); // If case the default schema is not the one specified by the // XML import file, try to get the right XML-schema and // namespace (this is done by parsing without validation) ImportExportNamespaceHandler nsHandler = new ImportExportNamespaceHandler(); factory.setSchema(null); parser = factory.newSAXParser(); xmlReader = parser.getXMLReader(); xmlReader.setContentHandler(nsHandler); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); xmlReader.parse(xmlInputSource); // If OK, extract the name and location of the schema String nsSpec = nsHandler.getNsSpec(); if (nsSpec == null || xsdPublicId.equals(nsSpec)) { throw ex; } String nsVersion = extractUriNameIndex(nsSpec); if (nsVersion.length() == 0) { throw ex; } String altXsdSystemId = settings.getStringWithParam("xsdSystemId", nsVersion); if ((altXsdSystemId == null) || (altXsdSystemId.equals(xsdSystemId))) { throw ex; } SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("Trying again using schema specification located at ")) .append(altXsdSystemId).toString()); // Try again to load, parse and validate the XML import file, // using the new schema specification schema = schemaFactory.newSchema(new StreamSource(altXsdSystemId)); factory.setSchema(schema); parser = factory.newSAXParser(); xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(errorHandler); xmlReader.parse(xmlInputSource); } SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", "XML Validation complete"); // Mapping file for Castor String mappingDir = settings.getString("mappingDir"); String mappingFileName = settings.getString("importExportMapping"); String mappingFile = mappingDir + mappingFileName; Mapping mapping = new Mapping(); // Load mapping and instantiate a Unmarshaller mapping.loadMapping(mappingFile); Unmarshaller unmar = new Unmarshaller(SilverPeasExchangeType.class); unmar.setMapping(mapping); unmar.setValidation(false); // Unmarshall the process model SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmar.unmarshal(xmlInputSource); SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", "Unmarshalling complete"); return silverpeasExchange; } catch (MappingException me) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_LOADING_XML_MAPPING_FAILED", "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me); } catch (MarshalException me) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_UNMARSHALLING_FAILED", "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me); } catch (ValidationException ve) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve); } catch (IOException ioe) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_LOADING_XML_MAPPING_FAILED", "XML Filename " + xmlFileName + ": " + ioe.getLocalizedMessage(), ioe); } catch (ParserConfigurationException ex) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + ex.getLocalizedMessage(), ex); } catch (SAXNotRecognizedException snre) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + snre.getLocalizedMessage(), snre); } catch (SAXNotSupportedException snse) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + snse.getLocalizedMessage(), snse); } catch (SAXException se) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + se.getLocalizedMessage(), se); } }
From source file:com.panet.imeta.trans.steps.xsdvalidator.XsdValidator.java
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (XsdValidatorMeta) smi;//from w ww . j a v a2 s . co m data = (XsdValidatorData) sdi; Object[] row = getRow(); if (row == null) // no more input to be expected... { setOutputDone(); return false; } if (first) { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Check if XML stream is given if (meta.getXMLStream() != null) { // Try to get XML Field index data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream()); // Let's check the Field if (data.xmlindex < 0) { // The field is unreachable ! logError(Messages.getString("XsdValidator.Log.ErrorFindingField") + "[" + meta.getXMLStream() //$NON-NLS-1$//$NON-NLS-2$ + "]"); throw new KettleStepException( Messages.getString("XsdValidator.Exception.CouldnotFindField", meta.getXMLStream())); //$NON-NLS-1$ //$NON-NLS-2$ } // Let's check that Result Field is given if (meta.getResultfieldname() == null) { // Result field is missing ! logError(Messages.getString("XsdValidator.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException( Messages.getString("XsdValidator.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ } // Is XSD file is provided? if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) { if (meta.getXSDFilename() == null) { logError(Messages.getString("XsdValidator.Log.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException( Messages.getString("XsdValidator.Exception.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Is XSD file exists ? FileObject xsdfile = null; try { xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename())); if (!xsdfile.exists()) { logError(Messages.getString("XsdValidator.Log.Error.XSDFileNotExists")); throw new KettleStepException( Messages.getString("XsdValidator.Exception.XSDFileNotExists")); } } catch (Exception e) { logError(Messages.getString("XsdValidator.Log.Error.GettingXSDFile")); throw new KettleStepException( Messages.getString("XsdValidator.Exception.GettingXSDFile")); } finally { try { if (xsdfile != null) xsdfile.close(); } catch (IOException e) { } } } } // Is XSD field is provided? if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) { if (meta.getXSDDefinedField() == null) { logError(Messages.getString("XsdValidator.Log.Error.XSDFieldMissing")); throw new KettleStepException(Messages.getString("XsdValidator.Exception.XSDFieldMissing")); } else { // Let's check if the XSD field exist // Try to get XML Field index data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField()); if (data.xsdindex < 0) { // The field is unreachable ! logError(Messages.getString("XsdValidator.Log.ErrorFindingXSDField", //$NON-NLS-1$ meta.getXSDDefinedField())); //$NON-NLS-2$ throw new KettleStepException(Messages.getString( "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$ } } } } else { // XML stream field is missing ! logError(Messages.getString("XsdValidator.Log.Error.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(Messages.getString("XsdValidator.Exception.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ } } boolean sendToErrorRow = false; String errorMessage = null; try { // Get the XML field value String XMLFieldvalue = getInputRowMeta().getString(row, data.xmlindex); boolean isvalid = false; // XSD filename String xsdfilename = null; if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) { xsdfilename = environmentSubstitute(meta.getXSDFilename()); } else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) { // Get the XSD field value xsdfilename = getInputRowMeta().getString(row, data.xsdindex); } // Get XSD filename FileObject xsdfile = null; String validationmsg = null; try { SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); xsdfile = KettleVFS.getFileObject(xsdfilename); File XSDFile = new File(KettleVFS.getFilename(xsdfile)); // Get XML stream Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue)); if (meta.getXMLSourceFile()) { // We deal with XML file // Get XML File File xmlfileValidator = new File(XMLFieldvalue); if (!xmlfileValidator.exists()) { logError(Messages.getString("XsdValidator.Log.Error.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException( Messages.getString("XsdValidator.Exception.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$ } sourceXML = new StreamSource(xmlfileValidator); } // Create XSD schema Schema SchematXSD = factoryXSDValidator.newSchema(XSDFile); if (meta.getXSDSource().equals(meta.NO_NEED)) { // ---Some documents specify the schema they expect to be validated against, // ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes //---Schema SchematXSD = factoryXSDValidator.newSchema(); SchematXSD = factoryXSDValidator.newSchema(); } // Create XSDValidator Validator XSDValidator = SchematXSD.newValidator(); // Validate XML / XSD XSDValidator.validate(sourceXML); isvalid = true; } catch (SAXException ex) { validationmsg = ex.getMessage(); logError("SAX Exception : " + ex); } catch (IOException ex) { validationmsg = ex.getMessage(); logError("SAX Exception : " + ex); } finally { try { if (xsdfile != null) xsdfile.close(); } catch (IOException e) { } } Object[] outputRowData = null; Object[] outputRowData2 = null; if (meta.getOutputStringField()) { // Output type=String if (isvalid) outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), environmentSubstitute(meta.getIfXmlValid())); else outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), environmentSubstitute(meta.getIfXmlInvalid())); } else { outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), isvalid); } if (meta.useAddValidationMessage()) outputRowData2 = RowDataUtil.addValueData(outputRowData, getInputRowMeta().size() + 1, validationmsg); else outputRowData2 = outputRowData; if (log.isRowLevel()) logRowlevel( Messages.getString("XsdValidator.Log.ReadRow") + " " + getInputRowMeta().getString(row)); // add new values to the row. putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s); } catch (KettleException e) { if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.toString(); } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001"); } else { logError(Messages.getString("XsdValidator.ErrorProcesing" + " : " + e.getMessage())); throw new KettleStepException(Messages.getString("XsdValidator.ErrorProcesing"), e); } } return true; }
From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java
public Unmarshaller getUnmarshaller() { Unmarshaller u = unmarshaller.get(); if (!isValidating() && u.getSchema() != null) { u.setSchema(null);/* www . j a v a 2 s . c o m*/ } else if (isValidating() && u.getSchema() == null) { // Load and set schema to validate against Schema schema; try { SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); List<URI> schemas = getAdditionalSchemas(); URL t2flowExtendedXSD = T2FlowParser.class.getResource(T2FLOW_EXTENDED_XSD); schemas.add(t2flowExtendedXSD.toURI()); List<Source> schemaSources = new ArrayList<>(); for (URI schemaUri : schemas) schemaSources.add(new StreamSource(schemaUri.toASCIIString())); Source[] sources = schemaSources.toArray(new Source[schemaSources.size()]); schema = schemaFactory.newSchema(sources); } catch (SAXException e) { throw new RuntimeException("Can't load schemas", e); } catch (URISyntaxException | NullPointerException e) { throw new RuntimeException("Can't find schemas", e); } u.setSchema(schema); } return u; }
From source file:nl.b3p.wms.capabilities.WMSCapabilitiesReader.java
/** Private method which validates a XML document at a given location. * * @param location String representing the location where the document can be found. * * @throws IOException/*from w w w. j av a 2s .c o m*/ * @throws SAXException */ // <editor-fold defaultstate="" desc="validate(String location) method."> private void validate(String location) throws IOException, SAXException { SchemaFactory factory = SchemaFactory.newInstance(SCHEMA_FACTORY); File schemaLocation = new File(SCHEMA_FILE); Schema schema = factory.newSchema(schemaLocation); Validator validator = schema.newValidator(); Source source = new StreamSource(new File(location)); validator.validate(source); }
From source file:csiro.pidsvc.mappingstore.Manager.java
/************************************************************************** * Generic processing methods.//from w w w .j av a 2 s.c om */ protected void validateRequest(String inputData, String xmlSchemaResourcePath) throws IOException, ValidationException { try { 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) { return new XsdSchemaResolver(type, namespaceURI, publicId, systemId, baseURI); } }); Schema schema = schemaFactory .newSchema(new StreamSource(getClass().getResourceAsStream(xmlSchemaResourcePath))); Validator validator = schema.newValidator(); _logger.trace("Validating XML Schema."); validator.validate(new StreamSource(new StringReader(inputData))); } catch (SAXException ex) { _logger.debug("Unknown format.", ex); throw new ValidationException("Unknown format.", ex); } }
From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java
/** * Loads and registers the integration tests that are found in the bundle at * the given location./*from ww w . jav a 2 s .c o m*/ * * @param dir * the directory containing the test files */ private List<IntegrationTest> loadIntegrationTestDefinitions(String dir) { Enumeration<?> entries = bundleContext.getBundle().findEntries(dir, "*.xml", true); // Schema validator setup SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = SiteImpl.class.getResource("/xsd/test.xsd"); Schema testSchema = null; try { testSchema = schemaFactory.newSchema(schemaUrl); } catch (SAXException e) { logger.error("Error loading XML schema for test definitions: {}", e.getMessage()); return Collections.emptyList(); } // Module.xml document builder setup DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setSchema(testSchema); docBuilderFactory.setNamespaceAware(true); // The list of tests List<IntegrationTest> tests = new ArrayList<IntegrationTest>(); while (entries != null && entries.hasMoreElements()) { URL entry = (URL) entries.nextElement(); // Validate and read the module descriptor ValidationErrorHandler errorHandler = new ValidationErrorHandler(entry); DocumentBuilder docBuilder; try { docBuilder = docBuilderFactory.newDocumentBuilder(); docBuilder.setErrorHandler(errorHandler); Document doc = docBuilder.parse(entry.openStream()); if (errorHandler.hasErrors()) { logger.warn("Error parsing integration test {}: XML validation failed", entry); continue; } IntegrationTestGroup test = IntegrationTestParser.fromXml(doc.getFirstChild()); test.setSite(this); test.setGroup(getName()); tests.add(test); } catch (SAXException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new IllegalStateException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } return tests; }
From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java
/** * Initializes the site components like modules, templates, actions etc. * /*w w w . ja v a2 s.c o m*/ * @throws Exception * if initialization fails */ private void initializeSiteComponents() throws Exception { logger.debug("Initializing site '{}'", this); final Bundle bundle = bundleContext.getBundle(); // Load i18n dictionary Enumeration<URL> i18nEnum = bundle.findEntries("site/i18n", "*.xml", true); while (i18nEnum != null && i18nEnum.hasMoreElements()) { i18n.addDictionary(i18nEnum.nextElement()); } // Prepare schema validator SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = SiteImpl.class.getResource("/xsd/module.xsd"); Schema moduleSchema = schemaFactory.newSchema(schemaUrl); // Set up the document builder DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setSchema(moduleSchema); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); // Load the modules final Enumeration<URL> e = bundle.findEntries("site", "module.xml", true); if (e != null) { while (e.hasMoreElements()) { URL moduleXmlUrl = e.nextElement(); int endIndex = moduleXmlUrl.toExternalForm().lastIndexOf('/'); URL moduleUrl = new URL(moduleXmlUrl.toExternalForm().substring(0, endIndex)); logger.debug("Loading module '{}' for site '{}'", moduleXmlUrl, this); // Load and validate the module descriptor ValidationErrorHandler errorHandler = new ValidationErrorHandler(moduleXmlUrl); docBuilder.setErrorHandler(errorHandler); Document moduleXml = docBuilder.parse(moduleXmlUrl.openStream()); if (errorHandler.hasErrors()) { logger.error("Errors found while validating module descriptor {}. Site '{}' is not loaded", moduleXml, this); throw new IllegalStateException("Errors found while validating module descriptor " + moduleXml); } // We need the module id even if the module initialization fails to log // a proper error message Node moduleNode = moduleXml.getFirstChild(); String moduleId = moduleNode.getAttributes().getNamedItem("id").getNodeValue(); Module module; try { module = ModuleImpl.fromXml(moduleNode); logger.debug("Module '{}' loaded for site '{}'", module, this); } catch (Throwable t) { logger.error("Error loading module '{}' of site {}", moduleId, identifier); if (t instanceof Exception) throw (Exception) t; throw new Exception(t); } // If module is disabled, don't add it to the site if (!module.isEnabled()) { logger.info("Found disabled module '{}' in site '{}'", module, this); continue; } // Make sure there is only one module with this identifier if (modules.containsKey(module.getIdentifier())) { logger.warn("A module with id '{}' is already registered in site '{}'", module.getIdentifier(), identifier); logger.error("Module '{}' is not registered due to conflicting identifier", module.getIdentifier()); continue; } // Check inter-module compatibility for (Module m : modules.values()) { // Check actions for (Action a : m.getActions()) { for (Action action : module.getActions()) { if (action.getIdentifier().equals(a.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines an action with id '{}'", new String[] { m.getIdentifier(), identifier, a.getIdentifier() }); } else if (action.getPath().equals(a.getPath())) { logger.warn("Module '{}' of site '{}' already defines an action at '{}'", new String[] { m.getIdentifier(), identifier, a.getPath() }); logger.error( "Module '{}' of site '{}' is not registered due to conflicting mountpoints", m.getIdentifier(), identifier); continue; } } } // Check image styles for (ImageStyle s : m.getImageStyles()) { for (ImageStyle style : module.getImageStyles()) { if (style.getIdentifier().equals(s.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines an image style with id '{}'", new String[] { m.getIdentifier(), identifier, s.getIdentifier() }); } } } // Check jobs for (Job j : m.getJobs()) { for (Job job : module.getJobs()) { if (job.getIdentifier().equals(j.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines a job with id '{}'", new String[] { m.getIdentifier(), identifier, j.getIdentifier() }); } } } } addModule(module); // Do this as last step since we don't want to have i18n dictionaries of // an invalid or disabled module in the site String i18nPath = UrlUtils.concat(moduleUrl.getPath(), "i18n"); i18nEnum = bundle.findEntries(i18nPath, "*.xml", true); while (i18nEnum != null && i18nEnum.hasMoreElements()) { i18n.addDictionary(i18nEnum.nextElement()); } } } else { logger.debug("Site '{}' has no modules", this); } // Look for a job scheduler logger.debug("Signing up for a job scheduling services"); schedulingServiceTracker = new SchedulingServiceTracker(bundleContext, this); schedulingServiceTracker.open(); // Load the tests if (!Environment.Production.equals(environment)) integrationTests = loadIntegrationTests(); else logger.info("Skipped loading of integration tests due to environment '{}'", environment); siteInitialized = true; logger.info("Site '{}' initialized", this); }
From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.ELTSchemaGridWidget.java
private boolean validateXML(InputStream xml, InputStream xsd) { try {/*from ww w . j a va2 s . c o m*/ SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return true; } catch (SAXException | IOException ex) { //MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage()); MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR | SWT.OK); dialog.setText(Messages.ERROR); dialog.setMessage(Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage()); logger.error(Messages.IMPORT_XML_FORMAT_ERROR); return false; } }
From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java
private static boolean validateXML(File configFile, InputStream xsdFile) throws IOException { Source schemaFile = new StreamSource(xsdFile); Source xmlFile = new StreamSource(configFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try {//from w w w . ja va2 s . c om Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(xmlFile); return true; //System.out.println(xmlFile.getSystemId() + " is valid"); } catch (SAXException e) { //System.out.println(xmlFile.getSystemId() + " is NOT valid"); //System.out.println("Reason: " + e.getLocalizedMessage()); return false; } }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Gets the <code>Schema</code> object for the provided <code>InputStream</code>. * //w w w . j a v a 2 s .c om * @param schemaStream * The Stream containing the schema. * @return Returns the <code>Schema</code> object. * @throws Exception * If anything fails. */ private static Schema getSchema(final InputStream schemaStream) throws Exception { if (schemaStream == null) { throw new Exception("No schema input stream provided"); } SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // set resource resolver to change schema-location-host sf.setResourceResolver(new SchemaBaseResourceResolver()); Schema theSchema = sf.newSchema(new SAXSource(new InputSource(schemaStream))); return theSchema; }