Skip to content

Commit

Permalink
add method to validate XML against a schema #2579
Browse files Browse the repository at this point in the history
  • Loading branch information
pdurbin committed Oct 30, 2015
1 parent 03cc7eb commit 80d8c0f
Show file tree
Hide file tree
Showing 3 changed files with 5,373 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/main/java/edu/harvard/iq/dataverse/util/xml/XmlValidator.java
@@ -0,0 +1,35 @@
package edu.harvard.iq.dataverse.util.xml;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import javax.xml.transform.Source;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;

public class XmlValidator {

private static final Logger logger = Logger.getLogger(XmlValidator.class.getCanonicalName());

public static boolean validateXml(String fileToValidate, String schemaToValidateAgainst) throws IOException, SAXException {

StreamSource schemaFile = new StreamSource(new File(schemaToValidateAgainst));
Source xmlFile = new StreamSource(new File(fileToValidate));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
logger.info(xmlFile.getSystemId() + " is valid");
return true;
} catch (SAXException ex) {
logger.info(xmlFile.getSystemId() + " is not valid: " + ex.getLocalizedMessage());
return false;
}
}

}

2 comments on commit 80d8c0f

@bencomp
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:D

@pdurbin
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I was saying at http://irclog.greptilian.com/friendlyjava/2015-10-30 this added 15 seconds to the build time. I'm comparing https://travis-ci.org/IQSS/dataverse/builds/88410542 to the previous build. I can tell it's slower locally too.

Please sign in to comment.