/** * Tries to read an XML input stream and validate and marshal it. Returns a valid object of type T * if succesful. * * @param <T> The type that will be validated and marshalled * @param docClass The class that represents the type T * @param xmlFile The xml file to be parsed * @param schemaFile The schema file to validate the XML file * @return An object of type T filled with the content from the XML document (if everything went * right that is) * @throws JAXBException If the JAXB framework threw an error * @throws SAXException If the SAX framework threw an error * @throws FileNotFoundException If specified input files could not be read */ public static <T> T validateAndUnmarshal(Class<T> docClass, File xmlFile, File schemaFile) throws JAXBException, SAXException, FileNotFoundException { // try to get the file if (!xmlFile.isFile() || !schemaFile.isFile()) { throw new FileNotFoundException("Cannot find input file"); } InputStream inputStream = new FileInputStream(xmlFile); // get the schema to validate the inputStream later on SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema; try { schema = sf.newSchema(schemaFile.toURI().toURL()); } catch (MalformedURLException ex) { // should never happen throw new FileNotFoundException("Cannot find input file"); } // create the unmarshaller that will parse/validate/marshal the inputStream String packageName = docClass.getPackage().getName(); Unmarshaller unmarshaller = JAXBContext.newInstance(packageName).createUnmarshaller(); // set the schema that the unmarshaller will use unmarshaller.setSchema(schema); // unmarshal and return the type return (T) unmarshaller.unmarshal(inputStream); }
/** Default constructor. */ private Modelica() { final String schemaPath = ScilabConstants.SCI.getAbsolutePath() + XcosConstants.XCOS_ETC + SCHEMA_FILENAME; JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(MODEL_CLASS_PACKAGE); marshaller = jaxbContext.createMarshaller(); unmarshaller = jaxbContext.createUnmarshaller(); Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new File(schemaPath)); marshaller.setSchema(schema); unmarshaller.setSchema(schema); /* * Customize the file to be handled by the xml2modelica and * modelicat tool. */ marshaller.setProperty(Marshaller.JAXB_ENCODING, LATIN1_ENCODING); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); } catch (JAXBException e) { throw new RuntimeException(e); } catch (SAXException e) { Logger.getLogger(Modelica.class.getName()).severe(e.toString()); } }
private static void validateSchema(Document document, String schemaFilePath) throws ValidateXMLSchemaException { // 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 InputStream is = factory.getClass().getResourceAsStream(schemaFilePath); Source schemaFile = new StreamSource(is); Schema schema; try { schema = factory.newSchema(schemaFile); } catch (SAXException e) { throw new ValidateXMLSchemaException(e); } // create a Validator instance, which can be used to validate an // instance document Validator validator = schema.newValidator(); // validate the DOM tree try { validator.validate(new DOMSource(document)); } catch (SAXException e) { throw new ValidateXMLSchemaException(e); } catch (IOException e) { throw new ValidateXMLSchemaException(e); } }
public static void main(String[] args) throws ParserConfigurationException { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = schemaFactory.newSchema(new File("customers.xsd")); Validator validator = schema.newValidator(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setSchema(schema); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File("new_customers.xml")); DOMSource domSource = new DOMSource(document); // DOMResult result = new DOMReult( ) validator.validate(domSource); } catch (SAXException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (ParserConfigurationException e) { e.printStackTrace(); } }
public List<Book> parse(InputStream is) throws Exception { /* * Validate against schema before it triggers implementation. */ StringBuffer xmlFile = new StringBuffer(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = bufferedReader.readLine()) != null) { xmlFile.append(line); } String xml = xmlFile.toString(); // validate against schema. try { URL schema = Resources.getResource("/catalog.xsd"); Validator validator = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema") .newSchema(schema) .newValidator(); Source source = new StreamSource(new CharArrayReader(xml.toCharArray())); validator.validate(source); } catch (Exception e) { this.errorHolder.addErrorMessage("Validation Error", e); return null; } // parse file into catalog ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); // ask extending class to parse return parseInternal(bais); }
/** * Run validation on the pass in xml using this schema * * @param xml String with a (hopefully) well formed and schema compliant xml document * @return * @throws SAXException * @throws IOException */ public Boolean validate(String xml) throws SAXException, IOException { // messages will contain this message if the schema is in a not yet supported format messages = "Not yet implemented"; if (this.type == types.RELAXNG_COMPACT) System.setProperty( "javax.xml.validation.SchemaFactory:" + XMLConstants.RELAXNG_NS_URI, "com.thaiopensource.relaxng.jaxp.CompactSyntaxSchemaFactory"); else System.setProperty( "javax.xml.validation.SchemaFactory:" + XMLConstants.RELAXNG_NS_URI, "com.thaiopensource.relaxng.jaxp.XMLSyntaxSchemaFactory"); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.RELAXNG_NS_URI); // change to use the schema stored here Schema schemaObj = factory.newSchema(new URL(schemaURL)); Validator validator = schemaObj.newValidator(); Source source = new StreamSource(new StringReader(xml)); try { validator.validate(source); return (true); } catch (SAXException ex) { messages = ex.getMessage(); return false; } }
protected void validateBindingsFileAgainstSchema(Source src) { String result = null; SchemaFactory sFact = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema theSchema; try { InputStream bindingsFileXSDInputStream = getClass().getClassLoader().getResourceAsStream(ECLIPSELINK_OXM_XSD); if (bindingsFileXSDInputStream == null) { bindingsFileXSDInputStream = getClass() .getClassLoader() .getResourceAsStream("org/eclipse/persistence/jaxb/" + ECLIPSELINK_OXM_XSD); } if (bindingsFileXSDInputStream == null) { fail("ERROR LOADING " + ECLIPSELINK_OXM_XSD); } Source bindingsFileXSDSource = new StreamSource(bindingsFileXSDInputStream); theSchema = sFact.newSchema(bindingsFileXSDSource); Validator validator = theSchema.newValidator(); validator.validate(src); } catch (Exception e) { e.printStackTrace(); if (e.getMessage() == null) { result = "An unknown exception occurred."; } result = e.getMessage(); } assertTrue("Schema validation failed unxepectedly: " + result, result == null); }
@Test public void testGetXmlAndValidateXmlSchema() throws IOException, ParserConfigurationException, SAXException { HttpClient httpClient = new HttpClient(); GetMethod get = new GetMethod("http://localhost/ch13personal/personal.xml"); Document document; try { httpClient.executeMethod(get); InputStream input = get.getResponseBodyAsStream(); // Parse the XML document into a DOM tree DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); document = parser.parse(input); } finally { get.releaseConnection(); } // 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 schemaFile = new StreamSource(new File("src/main/webapp/personal.xsd")); Schema schema = factory.newSchema(schemaFile); // create a Validator instance, which can be used to validate an // instance document Validator validator = schema.newValidator(); // validate the DOM tree validator.validate(new DOMSource(document)); }
private Validator createValidator(String actionXSD) throws SAXException { String readyXSD = createXsdForSpecificAction(actionXSD); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new StreamSource(new StringReader(readyXSD))); return schema.newValidator(); }
public static final boolean acceptsXmlNeptuneFile(File file, URL schemaURL) { if (schemaURL == null) { schemaURL = schemas.get(0); } try (FileInputStream in = new FileInputStream(file)) { Source xmlFile = new StreamSource(in); try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaURL); Validator validator = schema.newValidator(); validator.validate(xmlFile); Main.info(xmlFile.getSystemId() + " is valid"); return true; } catch (SAXException e) { Main.error(xmlFile.getSystemId() + " is NOT valid"); Main.error("Reason: " + e.getLocalizedMessage()); } catch (IOException e) { Main.error(xmlFile.getSystemId() + " is NOT valid"); Main.error("Reason: " + e.getLocalizedMessage()); } } catch (IOException e) { Main.error(e.getMessage()); } return false; }
/** * Method for instantiating and starting the application based from the information from the * xml-configuration file. */ public static final void start() { try { JAXBContext context = JAXBContext.newInstance(Application.class); Unmarshaller um = context.createUnmarshaller(); if (configurationFile != null && configurationFile.exists()) { SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema( TcLoadTester.class .getClassLoader() .getResource("com/siemens/tcloadtester/TcLoadTester.xsd")); um.setSchema(schema); app = (Application) um.unmarshal(new FileInputStream(configurationFile)); } else if (!gui) { throw new Exception("Configuration file does not exist."); } else { app = new Application(); } app.init(); } catch (Exception e) { if (gui) { UserInterface.DisplayError("Initialization error", e); UserInterface.loop(); } else { e.printStackTrace(); } } }
private Schema resolveLocalSchema(String schemaName, String schemaLanguage) { URL url = classLoaderService.locateResource(schemaName); if (url == null) { throw new XsdException( "Unable to locate schema [" + schemaName + "] via classpath", schemaName); } try { InputStream schemaStream = url.openStream(); try { StreamSource source = new StreamSource(url.openStream()); SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); return schemaFactory.newSchema(source); } catch (SAXException e) { throw new XsdException("Unable to load schema [" + schemaName + "]", e, schemaName); } catch (IOException e) { throw new XsdException("Unable to load schema [" + schemaName + "]", e, schemaName); } finally { try { schemaStream.close(); } catch (IOException e) { log.debugf("Problem closing schema stream [%s]", e.toString()); } } } catch (IOException e) { throw new XsdException( "Stream error handling schema url [" + url.toExternalForm() + "]", schemaName); } }
public void validate(final OMElement omElement, final File schemaFile) throws Exception { Element sourceElement; // if the OMElement is created using DOM implementation use it if (omElement instanceof ElementImpl) { sourceElement = (Element) omElement; } else { // else convert from llom to dom sourceElement = getDOMElement(omElement); } // Create a SchemaFactory capable of understanding WXS schemas. // Load a WXS schema, represented by a Schema instance. SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source source = new StreamSource(schemaFile); // Create a Validator object, which can be used to validate // an instance document. Schema schema = factory.newSchema(source); Validator validator = schema.newValidator(); // Validate the DOM tree. validator.validate(new DOMSource(sourceElement)); }
protected void validateXmlString(final String xml) throws Exception { if (getSchemaFile() == null) { LOG.warn("skipping validation, schema file not set"); return; } final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); final File schemaFile = new File(getSchemaFile()); LOG.debug("Validating using schema file: {}", schemaFile); final Schema schema = schemaFactory.newSchema(schemaFile); final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(true); saxParserFactory.setNamespaceAware(true); saxParserFactory.setSchema(schema); assertTrue("make sure our SAX implementation can validate", saxParserFactory.isValidating()); final Validator validator = schema.newValidator(); final ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes()); final Source source = new StreamSource(inputStream); validator.validate(source); }
public static List<TestCase> load(final InputSource inputSource) { try { final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final URL schemaUrl = Thread.currentThread().getContextClassLoader().getResource(SCHEMA_FILE); final Schema schema = schemaFactory.newSchema(schemaUrl); final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setIgnoringElementContentWhitespace(true); builderFactory.setIgnoringComments(true); builderFactory.setNamespaceAware(true); builderFactory.setCoalescing(true); builderFactory.setSchema(schema); final DocumentBuilder builder = builderFactory.newDocumentBuilder(); final Document doc = builder.parse(inputSource); final List<TestCase> testCases = new ArrayList<TestCase>(); final NodeList testCaseNodes = doc.getElementsByTagName(TEST_CASE_TAG); for (int i = 0; i < testCaseNodes.getLength(); ++i) { final Element testCaseElement = (Element) testCaseNodes.item(i); testCases.add(new TestCase(testCaseElement)); } return testCases; } catch (final ParserConfigurationException e) { throw new TestConfigurationException("Parser configuration failed", e); } catch (final SAXException e) { throw new TestConfigurationException("Parser error", e); } catch (final IOException e) { throw new TestConfigurationException("Error while reading file", e); } }
public static void validate(InputStream is) throws IndexerConfException { MyErrorHandler errorHandler = new MyErrorHandler(); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL url = IndexerConfBuilder.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()); } }
@Test public void testSuspendUntil() throws Exception { JAXBContext c = JAXBContext.newInstance("org.apache.hise.lang.xsd.htdt"); Unmarshaller m = c.createUnmarshaller(); m.setSchema( SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema") .newSchema(getClass().getResource("/ws-humantask-api-wsdl.xsd"))); SuspendUntil e = (SuspendUntil) m.unmarshal(getClass().getResourceAsStream("/suspendUntil.xml")); XQueryEvaluator ev = new XQueryEvaluator(); Date d = (Date) ev.evaluateExpression( "declare namespace xsd='http://www.w3.org/2001/XMLSchema'; xsd:dateTime('2009-01-01T12:59:34')", null) .get(0); System.out.println(d); e.getTime().getTimePeriod().addTo(d); Date d2 = (Date) ev.evaluateExpression( "declare namespace xsd='http://www.w3.org/2001/XMLSchema'; xsd:dateTime('2009-01-04T12:59:34')", null) .get(0); System.out.println(d2); Assert.assertEquals(d2, d); System.out.println(d); }
public ArrayList validateXML(String xmlMessage) { StringBuffer validationError = new StringBuffer(""); String result = "Pass"; ArrayList list = new ArrayList(); SubmitManufacturerPartyData sb = null; InputStream inFile = null; try { inFile = new ByteArrayInputStream(xmlMessage.getBytes()); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File("PartydataManufacturer.xsd")); JAXBContext ctx = JAXBContext.newInstance(new Class[] {SubmitManufacturerPartyData.class}); Unmarshaller um = ctx.createUnmarshaller(); um.setSchema(schema); sb = (SubmitManufacturerPartyData) um.unmarshal(inFile); } catch (SAXException e) { result = "Fail"; e.printStackTrace(); } catch (UnmarshalException umex) { result = "Fail"; System.out.println("---------- XML Validation Error -------------- "); System.out.println("#######" + umex.getLinkedException().getMessage()); umex.printStackTrace(); } catch (Exception e) { result = "Fail"; e.printStackTrace(); } list.add(sb); list.add(result); return list; }
/** * Cenverte o objeto informado para uma String que representa o XML do objeto. * * @param <T> Tipo generico que informa a classe * @param object O objeto a ser convertido. A classe deste objeto deve conter as anotações de * JAXB. * @param schemaLocation {@link URL} do schema. * @return * @throws JAXBException */ @SuppressWarnings("unchecked") public static <T> String marshal(T object, URL schemaLocation) throws JAXBException { Class<T> objClass = (Class<T>) object.getClass(); JAXBContext context = JAXBContext.newInstance(objClass); Marshaller marshaller = context.createMarshaller(); StringWriter sWriter = new StringWriter(); XmlSchema xmlSchema = objClass.getPackage().getAnnotation(XmlSchema.class); if (xmlSchema != null && xmlSchema.namespace() != null) { XmlType xmlType = objClass.getAnnotation(XmlType.class); if (xmlType != null && xmlType.name() != null) { QName qName = new QName(xmlSchema.namespace(), xmlType.name()); JAXBElement<T> elem = new JAXBElement<T>(qName, objClass, object); if (schemaLocation != null) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = schemaFactory.newSchema(schemaLocation); marshaller.setSchema(schema); } catch (SAXException e) { e.printStackTrace(); } } marshaller.marshal(elem, sWriter); return sWriter.toString(); } else { throw new JAXBException("The xmlType could not be identified in class annotation"); } } else { throw new JAXBException("The namespace could not be identified from package-info class"); } }
/** Private constructor */ private XMLReaders(int validate) { SAXParserFactory fac = SAXParserFactory.newInstance(); boolean val = false; // All JDOM parsers are namespace aware. fac.setNamespaceAware(true); switch (validate) { case 0: fac.setValidating(false); break; case 1: fac.setValidating(true); val = true; break; case 2: fac.setValidating(false); try { SchemaFactory sfac = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sfac.newSchema(); fac.setSchema(schema); val = true; } catch (SAXException se) { // we could not get a validating system, set the fac to null fac = null; } break; } jaxpfactory = fac; validates = val; }
@Test public void validateJaxbXmlAgainstSchema() throws Exception { final String schemaFile = getSchemaFile(); if (schemaFile == null) { LOG.warn("Skipping validation."); return; } LOG.debug("Validating against XSD: {}", schemaFile); javax.xml.bind.Unmarshaller unmarshaller = JaxbUtils.getUnmarshallerFor(getSampleClass(), null, true); final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); final Schema schema = factory.newSchema(new StreamSource(schemaFile)); unmarshaller.setSchema(schema); unmarshaller.setEventHandler( new ValidationEventHandler() { @Override public boolean handleEvent(final ValidationEvent event) { LOG.warn("Received validation event: {}", event, event.getLinkedException()); return false; } }); try { final InputSource inputSource = new InputSource(getSampleXmlInputStream()); final XMLFilter filter = JaxbUtils.getXMLFilterForClass(getSampleClass()); final SAXSource source = new SAXSource(filter, inputSource); @SuppressWarnings("unchecked") T obj = (T) unmarshaller.unmarshal(source); assertNotNull(obj); } finally { unmarshaller.setSchema(null); } }
public ClientSchemaValidationTube(WSBinding binding, WSDLPort port, Tube next) { super(binding, next); this.port = port; Source[] sources = null; if (port != null) { String primaryWsdl = port.getOwner().getParent().getLocation().getSystemId(); sources = getSchemaSources(primaryWsdl); for (Source source : sources) { LOGGER.fine("Constructing validation Schema from = " + source.getSystemId()); // printDOM((DOMSource)source); } } if (sources != null) { noValidation = false; SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { schema = sf.newSchema(sources); } catch (SAXException e) { throw new WebServiceException(e); } validator = schema.newValidator(); } else { noValidation = true; schema = null; validator = null; } }
private static void validateXMLWithURL(File nmlFile, String schemaUrl) { try { Source schemaFileSource = new StreamSource(schemaUrl); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(schemaFileSource); Validator validator = schema.newValidator(); Source xmlFileSource = new StreamSource(nmlFile); validator.validate(xmlFileSource); System.out.println( "**** File: " + nmlFile + " is VALID according to " + schemaUrl + "!!! ****"); } catch (Exception ex) { System.err.println( "Problem validating xml file: " + nmlFile.getAbsolutePath() + " according to " + schemaUrl + "!!!"); ex.printStackTrace(); System.exit(1); } }
/** * Loads the XML schema as a resource * * @returns the schema * @throws SiriusException */ public static javax.xml.validation.Schema getSchema() throws BeatsException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { return factory.newSchema(ObjectFactory.class.getClassLoader().getResource("sirius.xsd")); } catch (org.xml.sax.SAXException exc) { throw new BeatsException(exc); } }
@Test public void testSchemaFactory01() throws Exception { SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); InputSource is = new InputSource(Bug4966232.class.getResourceAsStream("test.xsd")); SAXSource ss = new SAXSource(is); Schema s = sf.newSchema(ss); Assert.assertNotNull(s); }
/** returns a JAXP 1.3 schema by parsing the specified resource. */ static Schema getSchema(String schemaResourceName) throws SAXException { SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { return sf.newSchema(Main.class.getResource(schemaResourceName)); } catch (SAXException se) { // this can only happen if there's a deployment error and the resource is missing. throw se; } }
/** * If this fails for you, check if you are using JDK 1.5. if so make sure you build from maven * with the -Pjava14 profile flag * * @throws SAXException * @throws IOException */ public void testValidation() throws SAXException, IOException { SchemaFactory schemaFactory = SchemaFactory.newInstance(XML_SCHEMA); schemaFactory.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true); Source muleXsd = new StreamSource(load("META-INF/mule.xsd")); Schema schema = schemaFactory.newSchema(muleXsd); Source muleRootTestXml = new StreamSource(load("org/mule/test/spring/mule-root-test.xml")); schema.newValidator().validate(muleRootTestXml); }
static Unmarshaller createConfigUnmarshaller() throws SAXException, JAXBException { JAXBContext ctx = JAXBContext.newInstance("com.stratuscom.harvester.config"); Unmarshaller um = ctx.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source source = new StreamSource(Bootstrap.class.getResourceAsStream("/schemas/config.xsd")); Schema schema = sf.newSchema(source); um.setSchema(schema); return um; }
/** * Parser the given schema and return in-memory representation of that schema. Compiling the * schema is very simple, just pass the path of schema to <code>newSchema()</code> function and it * will parse schema, check the validity of schema document as per the schema language, compute * in-memory representation and return it as <code>Schema</code> object. Note that If schema * imports/includes other schemas, those schemas will be parsed too. * * @param String path to schema file * @return Schema in-memory representation of schema. */ public static Schema compileSchema(String schema) throws SAXException { // Get the SchemaFactory instance which understands W3C XML Schema language SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); if (DEBUG) { System.out.println("schema factory instance obtained is " + sf); } // return sf.newSchema(new File(schema)); } // compileSchema
/** * Get an EQXML Schema object, for use with validation. * * @return Schema object. * @throws SAXException if unable to load schema. */ public static synchronized Schema getSchema() throws SAXException { if (SCHEMA == null) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); SCHEMA = schemaFactory.newSchema( Quakeml_1_2_Parser.class.getClassLoader().getResource(SCHEMA_RESOURCE_PATH)); } return SCHEMA; }