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); } }
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); }
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 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(); } }
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); } }
/** * 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 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 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)); }
@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)); }
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()); } }
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; }
/** * 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); }
/** Helper method that returns a validator for our XSD */ private Validator getValidator(int version, CaptureErrorHandler handler) throws SAXException { InputStream xsdStream = SdkRepository.getXsdStream(version); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdStream)); Validator validator = schema.newValidator(); if (handler != null) { validator.setErrorHandler(handler); } return validator; }
/** * Validates the given policy XML files against the standard XACML policies. * * @param policy Policy to validate * @return return false, If validation failed or XML parsing failed or any IOException occurs */ public static boolean validatePolicy(PolicyDTO policy) { try { if (!"true" .equalsIgnoreCase( (String) EntitlementServiceComponent.getEntitlementConfig() .getEngineProperties() .get(EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) { return true; } // there may be cases where you only updated the policy meta data in PolicyDTO not the // actual XACML policy String if (policy.getPolicy() == null || policy.getPolicy().trim().length() < 1) { return true; } // get policy version String policyXMLNS = getPolicyVersion(policy.getPolicy()); Map<String, Schema> schemaMap = EntitlementServiceComponent.getEntitlementConfig().getPolicySchemaMap(); // load correct schema by version Schema schema = schemaMap.get(policyXMLNS); if (schema != null) { // build XML document DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream stream = new ByteArrayInputStream(policy.getPolicy().getBytes()); Document doc = documentBuilder.parse(stream); // Do the DOM validation DOMSource domSource = new DOMSource(doc); DOMResult domResult = new DOMResult(); Validator validator = schema.newValidator(); validator.validate(domSource, domResult); if (log.isDebugEnabled()) { log.debug("XACML Policy validation succeeded with the Schema"); } return true; } else { log.error("Invalid Namespace in policy"); } } catch (SAXException e) { log.error("XACML policy is not valid according to the schema :" + e.getMessage()); } catch (IOException e) { // ignore } catch (ParserConfigurationException e) { // ignore } return false; }
private void serializeAndValidate(PrismObject<UserType> user, PrismContext prismContext) throws SchemaException, SAXException, IOException { String xmlString = prismContext.serializeObjectToString(user, PrismContext.LANG_XML); System.out.println("Serialized XML"); System.out.println(xmlString); Document xmlDocument = DOMUtil.parseDocument(xmlString); Schema javaxSchema = prismContext.getSchemaRegistry().getJavaxSchema(); Validator validator = javaxSchema.newValidator(); validator.setResourceResolver(prismContext.getEntityResolver()); validator.validate(new DOMSource(xmlDocument)); }
/** * Validates an XML fragment against a supplied schema. * * @param xml The fragment to validate * @param xsd The schema used for validation * @throws SAXException * @throws IOException */ protected void validate(final String xml, final String xsd) throws SAXException, IOException { final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema( new StreamSource(new ByteArrayInputStream(xsd.getBytes(Charset.forName(encoding))))); final Validator validator = schema.newValidator(); validator.validate( new StreamSource(new ByteArrayInputStream(xml.getBytes(Charset.forName(encoding))))); }
public static void validate(InputStream content) throws SAXException, IOException { try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema( VDBMetaData.class.getResource("/vdb-deployer.xsd")); // $NON-NLS-1$ Validator v = schema.newValidator(); v.validate(new StreamSource(content)); } finally { content.close(); } }
public void run(String xmlFile, String validationFile) { boolean valid = true; SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = sFactory.newSchema(new File(validationFile)); Validator validator = schema.newValidator(); Source source = new StreamSource(new File(xmlFile)); validator.validate(source); } catch (SAXException | IOException | IllegalArgumentException ex) { valid = false; } System.out.printf("XML file is %s.\n", valid ? "valid" : "invalid"); }
@Override public void enable() { try { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(myXMLSchemaFile.toURI().toURL()); myXMLSchemaValidator = schema.newValidator(); myEnabled = true; } catch (IOException | SAXException ex) { Logger.getLogger(ValidationModuleImpl.class.getName()).log(Level.SEVERE, null, ex); } notifyEvent(Event.EnabledUpdate); }
public boolean validate(String xmlDoc, String schemaPath) throws SAXException { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source schemaFile = new StreamSource(new File(schemaPath)); Source xmlFile = new StreamSource(new StringReader(xmlDoc)); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); try { validator.validate(xmlFile); return true; } catch (IOException e) { e.printStackTrace(); return false; } }
/** * Validates XML on a XMLschema * * @param xmlSchema * @param sourceXml */ public static void validateXmlOnSchema(Source xmlSchema, Source sourceXml) { Schema schema = newSchema(xmlSchema); try { schema.newValidator().validate(sourceXml); } catch (Exception e) { throw new RuntimeException( "Could not validate '" + sourceXml.getSystemId() + "' with '" + xmlSchema.getSystemId() + "'!", e); } }
/** * Validate against Coordinator XSD file * * @param xmlContent : Input coordinator xml * @throws CoordinatorJobException thrown if unable to validate coordinator xml */ private void validateXml(String xmlContent) throws CoordinatorJobException { javax.xml.validation.Schema schema = Services.get().get(SchemaService.class).getSchema(SchemaName.COORDINATOR); Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(new StringReader(xmlContent))); } catch (SAXException ex) { LOG.warn("SAXException :", ex); throw new CoordinatorJobException(ErrorCode.E0701, ex.getMessage(), ex); } catch (IOException ex) { LOG.warn("IOException :", ex); throw new CoordinatorJobException(ErrorCode.E0702, ex.getMessage(), ex); } }
static { try { ClassLoader loader = RequestValidator.class.getClassLoader(); URL url = loader.getResource(SCHEMA_RESOURCE); assertNotNull(url); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(url); VALIDATOR = schema.newValidator(); } catch (SAXException saxx) { // If the problem is resolution of xml:lang, check your internet // connection. throw (new IllegalStateException("Could not intialize schema validator: " + saxx)); } }
/** * Validates the code blocks document against the schema * * @param document The document to check * @throws RuntimeException If the validation failed */ private void validate(Document document) { try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = ClassLoader.getSystemResource("edu/mit/blocks/codeblocks/codeblocks.xsd"); Schema schema = schemaFactory.newSchema(schemaUrl); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
private void validate(Document document) throws IndexerConfException { try { 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); } }
private void testXSDConfigXML(String xmlFileName) throws SAXException, IOException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaResource = XMLConfigBuilderTest.class.getClassLoader().getResource("hazelcast-config-3.6.xsd"); InputStream xmlResource = XMLConfigBuilderTest.class.getClassLoader().getResourceAsStream(xmlFileName); Schema schema = factory.newSchema(schemaResource); Source source = new StreamSource(xmlResource); Validator validator = schema.newValidator(); try { validator.validate(source); } catch (SAXException ex) { fail(xmlFileName + " is not valid because: " + ex.toString()); } }
/** * Main entry point. Expects two arguments: the schema document, and the source document. * * @param args */ public static void main(String[] args) { try { if (args.length != 2) { printUsage(); return; } SchemaFactory schemaFactory; // Set a system property to force selection of the Saxon SchemaFactory implementation System.setProperty( "javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema", "com.saxonica.schema.SchemaFactoryImpl"); schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); schemaFactory.setErrorHandler(new LocalErrorHandler()); // create a grammar object. Schema schemaGrammar = schemaFactory.newSchema(new File(args[0])); System.err.println("Created Grammar object for schema : " + args[0]); Resolver resolver = new Resolver(); // create a validator to validate against the schema. ValidatorHandler schemaValidator = schemaGrammar.newValidatorHandler(); schemaValidator.setResourceResolver(resolver); schemaValidator.setErrorHandler(new LocalErrorHandler()); schemaValidator.setContentHandler( new LocalContentHandler(schemaValidator.getTypeInfoProvider())); System.err.println("Validating " + args[1] + " against grammar " + args[0]); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setNamespaceAware(true); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(schemaValidator); reader.parse(new InputSource(new File(args[1]).toURI().toString())); System.err.println("Validation successful"); } catch (SAXException saxe) { exit(1, "Error: " + saxe.getMessage()); } catch (Exception e) { e.printStackTrace(); exit(2, "Fatal Error: " + e); } }
/** * Validate the document against the namespaces referenced in it. * * @throws SAXException Validation error. * @throws IOException Error reading the XSD Sources. */ public void validate() throws SAXException, IOException { // Using the namespace URI list, create the XSD Source array used to // create the merged Schema instance... Source[] xsdSources = new Source[namespaces.size()]; for (int i = 0; i < namespaces.size(); i++) { xsdSources[i] = getNamespaceSource(namespaces.get(i)); } // Create the merged Schema instance and from that, create the Validator instance... SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(xsdSources); Validator validator = schema.newValidator(); // Validate the document... validator.validate(new DOMSource(document)); }
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; } }
public Iterable<Object> startWithValidation( final Reader in, String namespace, String schemaSource) throws SAXException { try { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream(schemaSource))); ValidatorHandler validator = schema.newValidatorHandler(); validator.setContentHandler(parser); validator.setErrorHandler(parser); AddNamespaceFilter filter = new AddNamespaceFilter(namespace); filter.setContentHandler(validator); return start(in, filter); } catch (IOException e) { throw new SAXException(tr("Failed to load XML schema."), e); } }