List of usage examples for javax.xml.validation Schema newValidator
public abstract Validator newValidator();
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 a v a 2 s .c o m 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 ww w . j a va 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.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();// ww w . j a v a2s . 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.XMLUtils.java
/** * Validate a Document with schema /*from w w w . jav a 2 s.co m*/ * @param xml to validate * @param schema to falidate from * @return a ValidationResult with validation result */ public static ValidationResult validateSchema(String xml, Schema schema) { try { ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("UTF-8")); Source xmlSource = new StreamSource(bais); schema.newValidator().validate(xmlSource); } catch (Exception e) { log.warn(e); return new ValidationResult(false, e.getMessage()); } return new ValidationResult(true); }
From source file:org.jdal.xml.XMLUtils.java
/** * Validate Document on schema//from w ww .ja va 2 s . c o m * @param doc to validate * @param schema for validation * @return a ValidationResult with validatin result */ public static ValidationResult validateSchema(Document doc, Schema schema) { try { Source xmlSource = new DOMSource(doc); schema.newValidator().validate(xmlSource); } catch (Exception e) { log.warn(e); return new ValidationResult(false, e.getMessage()); } return new ValidationResult(true); }
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. ja v a2 s. com*/ * @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 ww. jav a 2 s . c o m @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. * // w w w . j a v a2 s . c o m * @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.// www . j ava 2s . 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; }