SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.XML_DTD_NS_URI); Schema schema = schemaFactory.newSchema(new File( "xmlValidate.dtd")); Validator validator = schema.newValidator(); validator.validate(new StreamSource("xmlValidate.xml"));
@Override public void process(final InputStream in) throws IOException { try { validator.validate(new StreamSource(in)); } catch (final IllegalArgumentException | SAXException e) { valid.set(false); exception.set(e); } } });
public void validateModel(InputStreamProvider inputStreamProvider) throws Exception { Schema schema = createSchema(); Validator validator = schema.newValidator(); validator.validate(new StreamSource(inputStreamProvider.getInputStream())); }
/** * Validates a Role DOM against the XMLSchema. The schema is determined by the version of the * Role DOM * * @param doc * @throws IOException */ public void validateRoleRegistry(Document doc) throws IOException { if (versionMapRR == null) initializeSchemataRR(); XPathExpression expr = XMLXpathFactory.Singleton.getVersionExpressionRR(); String versionString; try { versionString = expr.evaluate(doc); } catch (XPathExpressionException e) { throw new IOException(e); } Schema schema = versionMapRR.get(versionString); Validator val = schema.newValidator(); try { val.validate(new DOMSource(doc)); } catch (SAXException e) { throw new IOException(e); } }
protected GeneralizationInfos parseXML(URL url) throws IOException { Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setNamespaceAware(true); factory.setIgnoringElementContentWhitespace(true); try { DocumentBuilder db = factory.newDocumentBuilder(); doc = db.parse(url.openStream()); VALIDATOR.validate(new DOMSource(doc)); } catch (Exception e) { throw new IOException(e.getMessage()); } NodeList nl = doc.getElementsByTagName(GENERALIZATION_INFOS_TAG); GeneralizationInfos gInfos = new GeneralizationInfos(); Node gInfosNode = nl.item(0); checkVersion(gInfosNode); NamedNodeMap attrMap = gInfosNode.getAttributes(); if (attrMap.getNamedItem(DATASOURCE_NAME_ATTR) != null) gInfos.setDataSourceName(attrMap.getNamedItem(DATASOURCE_NAME_ATTR).getTextContent()); if (attrMap.getNamedItem(DATASOURCE_NAMESPACE_NAME_ATTR) != null) gInfos.setDataSourceNameSpace( attrMap.getNamedItem(DATASOURCE_NAMESPACE_NAME_ATTR).getTextContent()); parseGeneralizationInfoNodes(gInfosNode, gInfos); return gInfos; }
public void validateModel(XMLStreamReader xmlStreamReader) throws Exception { Schema schema = createSchema(); Validator validator = schema.newValidator(); validator.validate(new StAXSource(xmlStreamReader)); }
static boolean validateAgainstXSD(InputStream xml, InputStream xsd) { try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return true; } catch(Exception ex) { return false; } }
/** * Validates a User/Group DOM against the XMLSchema. The schema is determined by the version of * the User/Group DOM * * @param doc * @throws IOException */ public void validateUserGroupRegistry(Document doc) throws IOException { if (versionMapUR == null) initializeSchemataUR(); XPathExpression expr = XMLXpathFactory.Singleton.getVersionExpressionUR(); String versionString = null; try { versionString = expr.evaluate(doc); } catch (XPathExpressionException e) { throw new IOException(e); // this should not happen } Schema schema = versionMapUR.get(versionString); Validator val = schema.newValidator(); try { val.validate(new DOMSource(doc)); } catch (SAXException e) { throw new IOException(e); // this should not happen } }
@Override public String isValid(String xml) { String errorMessage = ""; try { try { schema.newValidator().validate(new StreamSource(new ByteArrayInputStream(xml.getBytes(UTF_8)))); } catch (SAXException e) { errorMessage = e.getMessage(); } } catch (Exception e) { mockServerLogger.error("Exception validating JSON", e); return e.getClass().getSimpleName() + " - " + e.getMessage(); } return errorMessage; } }
@Override public ResourceTypeIdentifierResult identify(Representation representation) { try { validator.validate(new DOMSource((Node) representation.getAny())); } catch (SAXException ex) { return new ResourceTypeIdentifierResult(false, resourceTransformer); } catch (IOException ex) { LOG.severe(ex.getLocalizedMessage()); throw new SoapFault("Internal error", getSoapVersion().getReceiver()); } return new ResourceTypeIdentifierResult(true, resourceTransformer); }
/** * {@inheritDoc} */ @Override public void validateXML(String xmlContent) throws IOException, SAXException { try (StringReader stringReader = new StringReader(xmlContent)) { StreamSource streamSource = new StreamSource(stringReader); Validator validator = newValidator(newSchema()); validator.validate(streamSource); } }
public List<StoreDefinition> readStoreList(Reader input, boolean verifySchema) { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(input); if(verifySchema) { Validator validator = schema.newValidator(); validator.validate(new JDOMSource(doc)); } Element root = doc.getRootElement(); if(!root.getName().equals(STORES_ELMT)) throw new MappingException("Invalid root element: " + doc.getRootElement().getName()); List<StoreDefinition> stores = new ArrayList<StoreDefinition>(); for(Object store: root.getChildren(STORE_ELMT)) stores.add(readStore((Element) store)); for(Object view: root.getChildren(VIEW_ELMT)) stores.add(readView((Element) view, stores)); return stores; } catch(JDOMException e) { throw new MappingException(e); } catch(SAXException e) { throw new MappingException(e); } catch(IOException e) { throw new MappingException(e); } }
import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.*; ... URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"); Source xmlFile = new StreamSource(new File("web.xml")); SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); try { validator.validate(xmlFile); System.out.println(xmlFile.getSystemId() + " is valid"); } catch (SAXException e) { System.out.println(xmlFile.getSystemId() + " is NOT valid"); System.out.println("Reason: " + e.getLocalizedMessage()); }
private void validate(Document document) { // todo : add ability to disable validation... final String version = document.getDocumentElement().getAttribute( "version" ); final Validator validator = new ConfigXsdSupport().jpaXsd( version ).getSchema().newValidator(); List<SAXException> errors = new ArrayList<>(); validator.setErrorHandler( new ErrorHandlerImpl( errors ) ); try { validator.validate( new DOMSource( document ) ); } catch (SAXException e) { errors.add( e ); } catch (IOException e) { throw new PersistenceException( "Unable to validate persistence.xml", e ); } if ( errors.size() != 0 ) { //report all errors in the exception StringBuilder errorMessage = new StringBuilder( ); for ( SAXException error : errors ) { errorMessage.append( extractInfo( error ) ).append( '\n' ); } throw new PersistenceException( "Invalid persistence.xml.\n" + errorMessage.toString() ); } }
Validator validator = schema.newValidator(); MyErrorHandler handler = new MyErrorHandler(theContext); validator.setErrorHandler(handler); validator.validate(new StreamSource(new StringReader(encodedResource))); } catch (SAXParseException e) { SingleValidationMessage message = new SingleValidationMessage();
@SuppressWarnings("unchecked") public Cluster readCluster(Reader input, boolean verifySchema) { try { SAXBuilder builder = new SAXBuilder(false); Document doc = builder.build(input); if(verifySchema) { Validator validator = this.schema.newValidator(); validator.validate(new JDOMSource(doc)); } Element root = doc.getRootElement(); if(!root.getName().equals(CLUSTER_ELMT)) throw new MappingException("Invalid root element: " + doc.getRootElement().getName()); String name = root.getChildText(CLUSTER_NAME_ELMT); List<Zone> zones = new ArrayList<Zone>(); for(Element node: (List<Element>) root.getChildren(ZONE_ELMT)) zones.add(readZone(node)); List<Node> servers = new ArrayList<Node>(); for(Element node: (List<Element>) root.getChildren(SERVER_ELMT)) servers.add(readServer(node)); return new Cluster(name, servers, zones); } catch(JDOMException e) { throw new MappingException(e); } catch(SAXException e) { throw new MappingException(e); } catch(IOException e) { throw new MappingException(e); } }
public static void validate(final Node node, final String schemaFile) throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new URL(findResource(schemaFile).toURI().toASCIIString())); Validator validator = schema.newValidator(); // validate the DOM tree try { validator.validate(new DOMSource(node)); } catch (SAXException e) { ActiveMQClientLogger.LOGGER.errorOnXMLTransformInvalidConf(e); throw new IllegalStateException("Invalid configuration", e); } }
Validator v = schema.newValidator(); final SAXException[] error = {null}; v.setErrorHandler(new ErrorHandler() { v.validate(new DOMSource(fixupAttrs(data))); } catch (IOException x) { assert false : x;
/** * Validate DOM document * * @param document the DOM document to validate */ public void validateModel(DomDocument document) { Schema schema = getSchema(document); if (schema == null) { return; } Validator validator = schema.newValidator(); try { synchronized(document) { validator.validate(document.getDomSource()); } } catch (IOException e) { throw new ModelValidationException("Error during DOM document validation", e); } catch (SAXException e) { throw new ModelValidationException("DOM document is not valid", e); } }
// note that if your XML already declares the XSD to which it has to conform, then there's no need to declare the schemaName here void validate(String xml, String schemaName) throws Exception { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder parser = builderFactory .newDocumentBuilder(); // parse the XML into a document object Document document = parser.parse(new StringInputStream(xml)); SchemaFactory factory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // associate the schema factory with the resource resolver, which is responsible for resolving the imported XSD's factory.setResourceResolver(new ResourceResolver()); // note that if your XML already declares the XSD to which it has to conform, then there's no need to create a validator from a Schema object Source schemaFile = new StreamSource(getClass().getClassLoader() .getResourceAsStream(schemaName)); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); }