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()); }
Validator v = schema.newValidator(); final SAXException[] error = {null}; v.setErrorHandler(new ErrorHandler() { public @Override void warning(SAXParseException x) throws SAXException {} public @Override void error(SAXParseException x) throws SAXException { v.validate(new DOMSource(fixupAttrs(data))); } catch (IOException x) { assert false : x;
public static List validate( Source xml, URL schemaURL, boolean skipTargetNamespaceException, EntityResolver entityResolver) { try { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(schemaURL); Validator v = schema.newValidator(); if (entityResolver != null) { v.setResourceResolver( new EntityResolverToLSResourceResolver( v.getResourceResolver(), entityResolver)); } Handler handler = new Handler(skipTargetNamespaceException, entityResolver); v.setErrorHandler(handler); v.validate(xml); return handler.errors; } catch (SAXException e) { return exception(e); } catch (IOException e) { return exception(e); } }
@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; } }
/** * {@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); } }
Validator validator = schema.newValidator(); MyErrorHandler handler = new MyErrorHandler(theContext); validator.setErrorHandler(handler); String encodedResource; if (theContext.getResourceAsStringEncoding() == EncodingEnum.XML) { validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); }catch (SAXNotRecognizedException ex){ ourLog.warn("Jaxp 1.5 Support not found.",ex); validator.validate(new StreamSource(new StringReader(encodedResource))); } catch (SAXParseException e) { SingleValidationMessage message = new SingleValidationMessage();
public List<ValidationError> processValidation(Source[] xsdSources, File inputXML) throws ValidationException { ValidationHandler handler = new ValidationHandler(); try { SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); schemaFactory.setErrorHandler(handler); Schema schemaGrammar = schemaFactory.newSchema(xsdSources); Resolver resolver = new Resolver(); Validator schemaValidator = schemaGrammar.newValidator(); schemaValidator.setErrorHandler(handler); schemaValidator.setResourceResolver(resolver); schemaValidator.validate(new StreamSource(inputXML)); for (int i = 0; i < xsdSources.length; i++) { xsdSources[i] = null; } return handler.getErrors(); } catch (SAXException sae) { return handler.getErrors(); } catch (IOException ioe) { throw new ValidationException("Validation error", ioe); } }
/** * 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); } }
public static ValidationResult validate(Document doc, Source... schemas) throws IOException, SAXException { XMLErrorHandler errorHandler = new XMLErrorHandler(); Validator validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemas).newValidator(); try { validator.setErrorHandler(errorHandler); validator.validate(new DOMSource(doc)); return errorHandler; } finally { validator.reset(); } }
protected void validateSchema(final ValidationMethod method, final Resolver resolver, final byte[] schemaData, byte[] xmlData) throws SAXException, IOException { final SchemaFactory schemaFactory = SchemaFactory.newInstance(method.schemaLanguage); schemaFactory.setResourceResolver(resolver); final Schema schema = schemaFactory.newSchema(new StreamSource(new ByteArrayInputStream(schemaData))); final Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler()); validator.setResourceResolver(resolver); validator.validate(new StreamSource(new ByteArrayInputStream(xmlData))); }
private void validate(String[] schemaList) { // Create a new validator Validator validator = createSchema(schemaList).newValidator(); setFeature(validator, Constants.XERCES_FEATURE_PREFIX + "continue-after-fatal-error", true); validator.setErrorHandler(new MessageHandler()); validator.setResourceResolver(new SchemaResolver()); // Validate and catch the exceptions. MessageHandler will receive the errors and warnings. try { LOG.info("Validate " + getWebSourceCode() + " with schema " + StringUtils.join(schemaList, ",")); validator.validate(new StreamSource(getWebSourceCode().createInputStream())); } catch (SAXException e) { if (!containsMessage(e)) { createViolation(0, e.getMessage()); } } catch (IOException e) { throw new SonarException(e); } catch (UnrecoverableParseError e) { // ignore, message already reported. } }
public void validateModel(InputStreamProvider inputStreamProvider) throws Exception { Schema schema = createSchema(); Validator validator = schema.newValidator(); validator.validate(new StreamSource(inputStreamProvider.getInputStream())); }
@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); } } });
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 void validate(final byte[] xmlBytes) { final javax.xml.validation.Validator validator = schema.newValidator(); final ValidationExceptionBuilder errorHandler = new ValidationExceptionBuilder(); validator.setErrorHandler(errorHandler); try { validator.validate(new StreamSource(new ByteArrayInputStream(xmlBytes))); if (!errorHandler.errors.isEmpty()) throw errorHandler.build(); } catch (SAXException | IOException e) { throw new ValidationException(e); } }
public SAXParseException[] validate(Source source) throws IOException { javax.xml.validation.Validator validator = schema.newValidator(); ValidationErrorHandler errorHandler = new ValidationErrorHandler(); validator.setErrorHandler(errorHandler); try { validator.validate(source); return errorHandler.getErrors(); } catch (SAXException ex) { throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex); } } }
/** * Creates a new validator. * @param resolver The resolver for resources * @return A new validator */ private static Validator newValidator(final LSResourceResolver resolver) { try { final Validator validator = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema() .newValidator(); validator.setResourceResolver(resolver); return validator; } catch (final SAXException ex) { throw new IllegalStateException(ex); } } }
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 parseAndValidate(File xmlFile, ContentHandler handler) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new MySchemaResolver()); Schema schema = schemaFactory.newSchema(); Validator v = schema.newValidator(); v.setResourceResolver(schemaFactory.getResourceResolver()); InputSource is = new InputSource(new FileInputStream(xmlFile)); v.validate(new SAXSource(is), new SAXResult(handler)); }
private ResultadoValidacao valide(TipoSchema tipoSchema, Source source) throws IOException { ResultadoValidacao res = new ResultadoValidacao(); Schema schema = schemas.get(tipoSchema); Validator validator = schema.newValidator(); validator.setErrorHandler(res); validator.setResourceResolver(resourceResolver); try { validator.validate(source); } catch (SAXException e) { throw new IllegalStateException("Unexpected exception", e); } return res; }