List of usage examples for javax.xml.validation Validator validate
public void validate(Source source) throws SAXException, IOException
From source file:org.roda.core.common.validation.ValidationUtils.java
/** * Validates descriptive medatada (e.g. against its schema, but other * strategies may be used)/*from w ww . j ava 2s . c om*/ * * @param descriptiveMetadataType * * @param failIfNoSchema * @throws ValidationException */ public static ValidationReport validateDescriptiveBinary(ContentPayload descriptiveMetadataPayload, String descriptiveMetadataType, String descriptiveMetadataVersion, boolean failIfNoSchema) { ValidationReport ret = new ValidationReport(); InputStream inputStream = null; Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema(descriptiveMetadataType, descriptiveMetadataVersion); try { if (xmlSchema.isPresent()) { RodaErrorHandler errorHandler = new RodaErrorHandler(); try (InputStreamReader inputStreamReader = new InputStreamReader( new BOMInputStream(descriptiveMetadataPayload.createInputStream()))) { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RodaEntityResolver()); InputSource inputSource = new InputSource(inputStreamReader); Source source = new SAXSource(xmlReader, inputSource); Validator validator = xmlSchema.get().newValidator(); validator.setErrorHandler(errorHandler); validator.validate(source); ret.setValid(errorHandler.getErrors().isEmpty()); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } catch (SAXException e) { LOGGER.debug("Error validating descriptive binary " + descriptiveMetadataType, e); ret.setValid(false); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } } else { if (failIfNoSchema) { LOGGER.error( "Will fail validating descriptive metadata with type '{}' and version '{}' because couldn't find its schema", descriptiveMetadataType, descriptiveMetadataVersion); ret.setValid(false); ret.setMessage("No schema to validate " + descriptiveMetadataType); } else { LOGGER.debug( "Found no schema do validate descriptive metadata but will try to validate XML syntax..."); ret = isXMLValid(descriptiveMetadataPayload); } } } catch (IOException e) { LOGGER.error("Error validating descriptive metadata", e); ret.setValid(false); ret.setMessage(e.getMessage()); } finally { IOUtils.closeQuietly(inputStream); } return ret; }
From source file:org.roda.core.common.validation.ValidationUtils.java
/** * Validates preservation medatada (e.g. against its schema, but other * strategies may be used)/*from ww w .jav a2 s .com*/ * * @param failIfNoSchema * * @param descriptiveMetadataId * * @param failIfNoSchema * @throws ValidationException */ public static ValidationReport validatePreservationBinary(Binary binary, boolean failIfNoSchema) { ValidationReport report = new ValidationReport(); InputStream inputStream = null; try { Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema("premis-v2-0", null); if (xmlSchema.isPresent()) { inputStream = binary.getContent().createInputStream(); Source xmlFile = new StreamSource(inputStream); Validator validator = xmlSchema.get().newValidator(); RodaErrorHandler errorHandler = new RodaErrorHandler(); validator.setErrorHandler(errorHandler); try { validator.validate(xmlFile); report.setValid(errorHandler.getErrors().isEmpty()); for (SAXParseException saxParseException : errorHandler.getErrors()) { report.addIssue(convertSAXParseException(saxParseException)); } } catch (SAXException e) { LOGGER.error("Error validating preservation binary " + binary.getStoragePath(), e); report.setValid(false); for (SAXParseException saxParseException : errorHandler.getErrors()) { report.addIssue(convertSAXParseException(saxParseException)); } } } else if (failIfNoSchema) { report.setValid(false); report.setMessage("No schema to validate PREMIS"); } } catch (IOException e) { report.setValid(false); report.setMessage(e.getMessage()); } finally { IOUtils.closeQuietly(inputStream); } return report; }
From source file:org.sakaiproject.kernel.util.XSDValidator.java
/** * Validate a xml input stream against a supplied schema. * @param xml a stream containing the xml * @param schema a stream containing the schema * @return a list of errors or warnings, a 0 lenght string if none. *//*from w w w . j a v a 2s. co m*/ public static String validate(InputStream xml, InputStream schema) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); final StringBuilder errors = new StringBuilder(); try { SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA); Schema s = schemaFactory.newSchema(new StreamSource(schema)); Validator validator = s.newValidator(); validator.validate(new StreamSource(xml)); } catch (IOException e) { errors.append(e.getMessage()).append("\n"); } catch (SAXException e) { errors.append(e.getMessage()).append("\n"); } return errors.toString(); }
From source file:org.sakaiproject.tool.assessment.qti.helper.AuthoringHelper.java
private boolean validateImportXml(Document doc) throws SAXException, IOException { // 1. Lookup a factory for the W3C XML Schema language SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); // 2. Compile the schema. // Here the schema is loaded from a java.io.File, but you could use // a java.net.URL or a javax.xml.transform.Source instead. String schemaFile = VALIDATE_XSD_PATH + "qtiv1p2.xsd"; log.debug("schemaFile = " + schemaFile); Schema schema = factory.newSchema( new StreamSource(AuthoringHelper.class.getClassLoader().getResourceAsStream(schemaFile))); // 3. Get a validator from the schema. Validator validator = schema.newValidator(); // 4. Parse the document you want to check. Source source = new DOMSource(doc); // 5. Check the document try {/*from ww w .j ava 2 s . c o m*/ validator.validate(source); log.debug("The xml is valid."); return true; } catch (SAXException ex) { log.debug("The xml is not valid QTI format.", ex); } return false; }
From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl.java
private static void parseAndValidate(EdfiRecordParserImpl parser, Schema schema) throws XmlParseException { Validator validator = schema.newValidator(); validator.setErrorHandler(parser);//from w w w .ja v a2 s . c o m try { validator.validate(new StAXSource(parser)); } catch (SAXException e) { throw new XmlParseException("Exception while processing the xml file", e); } catch (IOException e) { throw new XmlParseException("Exception while accessing the xml file", e); } catch (XMLStreamException e) { throw new XmlParseException("Exception while processing the xml file", e); } }
From source file:org.sonar.plugins.xml.checks.XmlSchemaCheck.java
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 {/* www. jav a 2s .c o m*/ 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. } }
From source file:org.wso2.carbon.apimgt.gateway.mediators.XMLSchemaValidator.java
/** * This method validates the request payload xml with the relevant xsd. * * @param messageContext This message context contains the request message properties of the relevant * API which was enabled the XML_Validator message mediation in flow. * @param bufferedInputStream Buffered input stream to be validated. * @throws APIMThreatAnalyzerException Exception might be occurred while parsing the xml payload. */// w w w. j ava 2s .c o m private boolean validateSchema(MessageContext messageContext, BufferedInputStream bufferedInputStream) throws APIMThreatAnalyzerException { String xsdURL; Schema schema; SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.XSD_URL); if (messageProperty == null) { return true; } else { if (String.valueOf(messageProperty).isEmpty()) { return true; } else { xsdURL = String.valueOf(messageProperty); URL schemaFile = new URL(xsdURL); schema = schemaFactory.newSchema(schemaFile); Source xmlFile = new StreamSource(bufferedInputStream); Validator validator = schema.newValidator(); validator.validate(xmlFile); } } } catch (SAXException | IOException e) { throw new APIMThreatAnalyzerException("Error occurred while parsing XML payload : " + e); } return true; }
From source file:org.wso2.carbon.automation.engine.test.configuration.ConfigurationXSDValidatorTest.java
@Test(groups = "context.unit.test", description = "Upload aar service and verify deployment") public void validateAutomationXml() throws IOException, SAXException { boolean validated = false; URL schemaFile = validateXsdFile.toURI().toURL(); Source xmlFile = new StreamSource(configXmlFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); try {//w w w . ja v a 2s. co m validator.validate(xmlFile); validated = true; } catch (SAXException e) { log.error(e.getStackTrace()); throw new SAXException(e); } Assert.assertTrue(validated); }
From source file:org.wso2.carbon.governance.generic.util.Util.java
public static boolean validateOMContent(OMElement omContent, Validator validator) { try {//from w ww . j a va2 s .c om InputStream is = new ByteArrayInputStream(omContent.toString().getBytes("utf-8")); Source xmlFile = new StreamSource(is); if (validator != null) { validator.validate(xmlFile); } } catch (SAXException e) { log.error("Unable to validate the given xml configuration ", e); return false; } catch (UnsupportedEncodingException e) { log.error("Unsupported content"); return false; } catch (IOException e) { log.error("Unable to validate the given file"); return false; } return true; }
From source file:org.wso2.carbon.governance.lcm.util.CommonUtil.java
public static boolean validateOMContent(OMElement omContent, Validator validator) { try {/*from w w w .j ava2s . co m*/ InputStream is = new ByteArrayInputStream(omContent.toString().getBytes("utf-8")); Source xmlFile = new StreamSource(is); if (validator != null) { validator.validate(xmlFile); } } catch (SAXException e) { log.error("Unable to parse the XML configuration. Please validate the XML configuration", e); return false; } catch (UnsupportedEncodingException e) { log.error("Unsupported content", e); return false; } catch (IOException e) { log.error("Unable to parse the XML configuration. Please validate the XML configuration", e); return false; } return true; }