/** * Attempts to validate the given XML string using Java's XML validation facility. Requires Java * 1.5+. * * @param xml The XML string to validate. * @param label String describing the type of XML being validated. * @return whether or not validation was successful. */ public static boolean validateXML(String xml, String label) { if (label == null) label = "XML"; Exception exception = null; // get path to schema from root element using SAX LOGGER.info("Parsing schema path"); ValidationSAXHandler saxHandler = new ValidationSAXHandler(); try { // Java XML factories are not declared to be thread safe SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); InputStream is = new ByteArrayInputStream(xml.getBytes(Constants.ENCODING)); saxParser.parse(is, saxHandler); } catch (ParserConfigurationException exc) { exception = exc; } catch (SAXException exc) { exception = exc; } catch (IOException exc) { exception = exc; } if (exception != null) { LOGGER.warn("Error parsing schema path from {}", label, exception); return false; } String schemaPath = saxHandler.getSchemaPath(); if (schemaPath == null) { LOGGER.error("No schema path found. Validation cannot continue."); return false; } LOGGER.info(schemaPath); LOGGER.info("Validating {}", label); // compile the schema URI schemaLocation = null; try { schemaLocation = new URI(schemaPath); } catch (URISyntaxException exc) { LOGGER.info("Error accessing schema at {}", schemaPath, exc); return false; } Schema schema = schemas.get().get(schemaLocation); if (schema == null) { try { schema = FACTORY.newSchema(schemaLocation.toURL()); schemas.get().put(schemaLocation, schema); } catch (MalformedURLException exc) { LOGGER.info("Error parsing schema at {}", schemaPath, exc); return false; } catch (SAXException exc) { LOGGER.info("Error parsing schema at {}", schemaPath, exc); return false; } } // get a validator from the schema Validator validator = schema.newValidator(); // prepare the XML source StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader); SAXSource source = new SAXSource(is); // validate the XML ValidationErrorHandler errorHandler = new ValidationErrorHandler(); validator.setErrorHandler(errorHandler); try { validator.validate(source); } catch (IOException exc) { exception = exc; } catch (SAXException exc) { exception = exc; } final int errors = errorHandler.getErrorCount(); if (errors > 0) { LOGGER.info("Error validating document: {} errors found", errors); return false; } else LOGGER.info("No validation errors found."); return errorHandler.ok(); }