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(); } }
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(); }
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)); }
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)); }
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); } }
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; }
private static String[] validateXMLWorker(InputStream is, Schema schema) { final Vector<String> validationMsgs = new Vector<String>(); Validator validator = schema.newValidator(); validator.setErrorHandler( new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { validationMsgs.add("WARNING: " + exception.getMessage()); } @Override public void error(SAXParseException exception) throws SAXException { validationMsgs.add("ERROR: " + exception.getMessage()); } @Override public void fatalError(SAXParseException exception) throws SAXException { validationMsgs.add("FATAL: " + exception.getMessage()); } }); try { validator.validate(new StreamSource(is)); } catch (Exception e) { validationMsgs.add("SOURCE: " + e.getMessage()); } return validationMsgs.toArray(new String[validationMsgs.size()]); }
protected ClientSchemaValidationTube(ClientSchemaValidationTube that, TubeCloner cloner) { super(that, cloner); this.port = that.port; this.schema = that.schema; this.validator = schema.newValidator(); this.noValidation = that.noValidation; }
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; } }
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 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 ServerSchemaValidationTube( WSEndpoint endpoint, WSBinding binding, SEIModel seiModel, WSDLPort wsdlPort, Tube next) { super(binding, next); this.seiModel = seiModel; this.wsdlPort = wsdlPort; if (endpoint.getServiceDefinition() != null) { MetadataResolverImpl mdresolver = new MetadataResolverImpl(endpoint.getServiceDefinition()); Source[] sources = getSchemaSources(endpoint.getServiceDefinition(), mdresolver); for (Source source : sources) { LOGGER.fine("Constructing service validation schema from = " + source.getSystemId()); // printDOM((DOMSource)source); } if (sources.length != 0) { noValidation = false; sf.setResourceResolver(mdresolver); try { schema = sf.newSchema(sources); } catch (SAXException e) { throw new WebServiceException(e); } validator = schema.newValidator(); return; } } noValidation = true; schema = null; validator = null; }
/** * 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 ServerSchemaValidationTube(ServerSchemaValidationTube that, TubeCloner cloner) { super(that, cloner); // this.docs = that.docs; this.schema = that.schema; // Schema is thread-safe this.validator = schema.newValidator(); this.noValidation = that.noValidation; this.seiModel = that.seiModel; this.wsdlPort = that.wsdlPort; }
/** * 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); }
@Override public void validate(final Document document, final Schema schema) { try { Validator validator = schema.newValidator(); validator.validate(domSourceFactory.newDOMSource(document)); } catch (Exception e) { throw new DescriptorValidationFailedException( "Validation of stub descriptor failed - XSD validation failed.", e); } }
protected static <T extends Node> T validate(T d, Schema schema) throws LoadFailedException { try { schema.newValidator().validate(new DOMSource(d)); return d; } catch (SAXException e) { throw new LoadFailedException(e); } catch (IOException e) { throw new LoadFailedException(e); } }
/** * 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; }
/** * 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))))); }
/** 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; }
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)); }
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); }
/** * 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); } }
/** * 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); } }
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; } }
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)); } }