1 package org.jivesoftware.messenger.plugin; 2 3 import java.io.File ; 4 import java.net.MalformedURLException ; 5 import java.net.URL ; 6 7 import javax.xml.parsers.SAXParserFactory ; 8 9 import org.dom4j.Document; 10 import org.dom4j.DocumentException; 11 import org.dom4j.io.SAXReader; 12 import org.dom4j.io.SAXWriter; 13 import org.jivesoftware.util.Log; 14 import org.xml.sax.ContentHandler ; 15 import org.xml.sax.ErrorHandler ; 16 import org.xml.sax.Locator ; 17 import org.xml.sax.SAXParseException ; 18 19 import com.sun.msv.reader.util.GrammarLoader; 20 import com.sun.msv.reader.util.IgnoreController; 21 import com.sun.msv.verifier.DocumentDeclaration; 22 import com.sun.msv.verifier.Verifier; 23 24 public class UserSchemaValidator { 25 private Document doc; 26 private String schema; 27 28 UserSchemaValidator(String usersFile, String schemaFile) throws MalformedURLException , DocumentException { 29 URL usersURL = new File (usersFile).toURL(); 30 URL schemaURL = this.getClass().getClassLoader().getResource(schemaFile); 31 32 SAXReader reader = new SAXReader(); 33 doc = reader.read(usersURL); 34 schema = schemaURL.toExternalForm(); 35 } 36 37 boolean validate() { 38 try { 39 SAXParserFactory saxFactory = SAXParserFactory.newInstance(); 40 saxFactory.setNamespaceAware(true); 41 DocumentDeclaration docDeclaration = GrammarLoader.loadVGM(schema, new IgnoreController() { 42 public void error(Locator [] locations, 43 String message, 44 Exception exception) { 45 Log.error("ERROR: " + message); 46 } 47 48 public void error(Locator [] locations, String message) { 49 Log.error("WARNING: " + message); 50 } 51 }, saxFactory); 52 53 ValidatorErrorHandler validatorErrorHandler = new ValidatorErrorHandler(); 54 Verifier verifier = new Verifier(docDeclaration, validatorErrorHandler); 55 56 SAXWriter writer = new SAXWriter((ContentHandler ) verifier); 57 writer.setErrorHandler(validatorErrorHandler); 58 59 writer.write(doc); 60 if (verifier.isValid()) { 61 return true; 62 } else { 63 Log.error(doc.getName() + " is invalid."); 64 return false; 65 } 66 } catch (Exception e) { 67 Log.error(e); 68 return false; 69 } 70 } 71 72 private class ValidatorErrorHandler implements ErrorHandler { 73 public void error(SAXParseException e) { 74 Log.error("ERROR:" + e); 75 } 76 77 public void fatalError(SAXParseException e) { 78 Log.error("Fatal:" + e); 79 } 80 81 public void warning(SAXParseException e) { 82 Log.error("Warning:" + e); 83 } 84 } 85 } 86 | Popular Tags |