[bvalid-codewatch] SF.net SVN: bvalid: [18] trunk
Status: Beta
Brought to you by:
cwilper
|
From: <cw...@us...> - 2006-05-01 06:58:01
|
Revision: 18 Author: cwilper Date: 2006-04-30 23:57:49 -0700 (Sun, 30 Apr 2006) ViewCVS: http://svn.sourceforge.net/bvalid/?rev=18&view=rev Log Message: ----------- command-line interface works Modified Paths: -------------- trunk/build.xml trunk/src/java/net/sf/bvalid/BValid.java trunk/src/java/net/sf/bvalid/catalog/FileSchemaIndex.java trunk/src/test/net/sf/bvalid/ValidatorFactoryTest.java Added Paths: ----------- trunk/src/bin/ trunk/src/bin/bvalid trunk/src/bin/bvalid.bat trunk/src/java/net/sf/bvalid/BValid.properties Modified: trunk/build.xml =================================================================== --- trunk/build.xml 2006-04-28 05:07:57 UTC (rev 17) +++ trunk/build.xml 2006-05-01 06:57:49 UTC (rev 18) @@ -31,6 +31,15 @@ <copy todir="build/classes"> <fileset dir="src/config"/> </copy> + <copy file="src/java/net/sf/bvalid/BValid.properties" tofile="build/classes/net/sf/bvalid/BValid.properties"/> + <propertyfile file="build/version.properties"> + <entry key="buildDate" type="date" value="now"/> + </propertyfile> + <replace file="build/classes/net/sf/bvalid/BValid.properties" + value="value not found in version.properties" + propertyFile="build/version.properties"> + <replacefilter token="@buildDate@" property="buildDate"/> + </replace> </target> <target name="testclasses" @@ -48,6 +57,10 @@ <copy todir="dist/lib"> <fileset dir="lib"/> </copy> + <copy todir="dist"> + <fileset dir="src/bin"/> + </copy> + <chmod dir="dist" perm="ugo+x" includes="bvalid"/> <jar jarfile="dist/bvalid.jar" basedir="build/classes"/> </target> Added: trunk/src/bin/bvalid =================================================================== --- trunk/src/bin/bvalid (rev 0) +++ trunk/src/bin/bvalid 2006-05-01 06:57:49 UTC (rev 18) @@ -0,0 +1,20 @@ +#!/bin/sh + +if [ -z "$BVALID_HOME" ]; then + BVALID_HOME=. +fi + +if [ ! -f "$BVALID_HOME/bvalid.jar" ]; then + echo "ERROR: $BVALID_HOME/bvalid.jar was not found." + echo "NOTE : To run bvalid from any directory, BVALID_HOME must be defined." + exit 1 +fi + +(exec java -Xms64m -Xmx96m \ + -cp "$BVALID_HOME/bvalid.jar" \ + -Djava.endorsed.dirs="$BVALID_HOME/lib" \ + -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl \ + -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl \ + net.sf.bvalid.BValid $1 $2 $3 $4 $5 $6 $7 $8 $9) + +exit $? Property changes on: trunk/src/bin/bvalid ___________________________________________________________________ Name: svn:executable + * Added: trunk/src/bin/bvalid.bat =================================================================== --- trunk/src/bin/bvalid.bat (rev 0) +++ trunk/src/bin/bvalid.bat 2006-05-01 06:57:49 UTC (rev 18) @@ -0,0 +1,28 @@ +@echo off + +goto checkEnv + +:envOk +java -Xms64m -Xmx96m -cp "%BVALID_HOME%\bvalid.jar" -Djava.endorsed.dirs="%BVALID_HOME%\lib" -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl net.sf.bvalid.BValid %1 %2 %3 %4 %5 %6 %7 %8 %9 +if errorlevel 1 goto endWithError +goto end + +:checkEnv +if "%BVALID_HOME%" == "" goto setHome + +:checkJarExists +if not exist "%BVALID_HOME%\bvalid.jar" goto jarNotFound +goto envOk + +:setHome +set BVALID_HOME=. +goto checkJarExists + +:jarNotFound +echo ERROR: %BVALID_HOME%\bvalid.jar was not found. +echo NOTE: To run bvalid from any directory, BVALID_HOME must be defined. + +:endWithError +exit /B 1 + +:end Modified: trunk/src/java/net/sf/bvalid/BValid.java =================================================================== --- trunk/src/java/net/sf/bvalid/BValid.java 2006-04-28 05:07:57 UTC (rev 17) +++ trunk/src/java/net/sf/bvalid/BValid.java 2006-05-01 06:57:49 UTC (rev 18) @@ -3,53 +3,290 @@ import java.io.*; import java.util.*; -import net.sf.bvalid.catalog.DiskSchemaCatalog; -import net.sf.bvalid.catalog.FileSchemaIndex; -import net.sf.bvalid.catalog.MemorySchemaCatalog; -import net.sf.bvalid.catalog.SchemaIndex; -import net.sf.bvalid.locator.CachingSchemaLocator; -import net.sf.bvalid.locator.SchemaLocator; -import net.sf.bvalid.locator.URLSchemaLocator; +import org.apache.log4j.Logger; /** - * Test class. + * Command-line utility for validating instance documents. * * @author cw...@cs... */ public class BValid { - public static void main(String[] args) throws Exception { + private static Logger _LOG = Logger.getLogger(BValid.class.getName()); + private Options _opts; + private String _version; + private String _buildDate; + + public BValid(String[] args) throws ArgException { + + // get version and buildDate from properties + Properties props = new Properties(); + InputStream in = BValid.class.getClassLoader().getResourceAsStream("net/sf/bvalid/BValid.properties"); + try { + props.load(in); + _version = props.getProperty("bvalid.version"); + _buildDate = props.getProperty("bvalid.buildDate"); + } catch (Exception e) { + throw new RuntimeException("Error loading bvalid.properties"); + } finally { + try { in.close(); } catch (Exception e) { } + } + + _opts = new Options(args); + } + + private String getVersionLine() { + return "BValid version " + _version + " (build date: " + _buildDate + ")"; + } + + private void showVersion() { + System.out.println(getVersionLine()); + } + + private void showUsage() { + System.out.println("Usage: bvalid [OPTIONS] LANG XMLFILE"); + System.out.println(" Or: bvalid --version"); + System.out.println(" Or: bvalid --help"); + System.out.println(""); + System.out.println("Where:"); + System.out.println(" LANG a supported schema language, such as xsd"); + System.out.println(" XMLFILE the path to the instance file to validate"); + System.out.println(""); + System.out.println("Options:"); + System.out.println(" -cf, --cache-files Cache schema files locally"); + System.out.println(" -co, --cache-objects Cache parsed grammar objects in memory"); + System.out.println(" -am, --allow-missing Allow missing referenced schemas. If the instance"); + System.out.println(" includes references to schemas that can't be found,"); + System.out.println(" this will skip them rather than failing validation."); + System.out.println(" --repeat=n Repeat the validation n times (for testing)"); + System.out.println(" --schema=file Use the given schema file (url or filename)"); + System.out.println(" -v, --version Print version and exit (exclusive option)"); + System.out.println(" -h, --help Print help and exit (exclusive option)"); + System.out.println(""); + } + + public void run() throws Exception { + + if (_opts.showVersion()) { + showVersion(); + } else if (_opts.showUsage()) { + showVersion(); + System.out.println(); + showUsage(); + } else { + _LOG.info(getVersionLine()); + + // construct our validator + Validator validator; + Map vopts = new HashMap(); + if (_opts.cacheObjects()) { + vopts.put(ValidatorOption.CACHE_PARSED_GRAMMARS, "true"); + } + if (_opts.allowMissing()) { + vopts.put(ValidatorOption.FAIL_ON_MISSING_REFERENCED, "false"); + } + File cacheDir = null; + if (_opts.cacheFiles()) { + cacheDir = File.createTempFile("bvalid-schemaCache", ""); + cacheDir.delete(); + cacheDir.mkdir(); + validator = ValidatorFactory.getValidator(_opts.getLang(), + cacheDir, + vopts); + } else { + validator = ValidatorFactory.getValidator(_opts.getLang(), + vopts); + } + + try { + runValidation(validator, + _opts.getXMLFile(), + _opts.getSchema(), + _opts.getRepeat()); + } finally { + + // if we created cache dir, clean it up + if (cacheDir != null && cacheDir.isDirectory()) { + try { + File[] files = cacheDir.listFiles(); + for (int i = 0; i < files.length; i++) { + files[i].delete(); + } + cacheDir.delete(); + } catch (Exception e) { } + } + } + } + } + + private void runValidation(Validator validator, + File xmlFile, + String schema, + int times) throws Exception { + + long startTime = System.currentTimeMillis(); + for (int i = 0; i < times; i++) { + + long st = System.currentTimeMillis(); + try { + InputStream in = new FileInputStream(xmlFile); + if (schema != null) { + validator.validate(in, schema); + } else { + validator.validate(in); + } + long ms = System.currentTimeMillis() - st; + _LOG.info("Validation of " + xmlFile.getPath() + " succeeded in " + ms + "ms."); + } catch (ValidationException e) { + long ms = System.currentTimeMillis() - st; + _LOG.error("Validation of " + xmlFile.getPath() + " failed in " + ms + "ms.\n" + e.getMessage()); + } + } + long total = System.currentTimeMillis() - startTime; + long msPerDoc = total / times; + _LOG.info("Overall validation rate: " + msPerDoc + "ms/doc"); + } + + public static void main(String[] args) { + // tell commons-logging to use log4j System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.Log4jFactory"); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger"); - Map options = new HashMap(); - options.put(ValidatorOption.CACHE_PARSED_GRAMMARS, "true"); + int errorLevel = 1; + try { + BValid bvalid = new BValid(args); + bvalid.run(); + errorLevel = 0; + } catch (ArgException e) { + System.out.println("bvalid: " + e.getMessage() + " ( -h to show usage )"); + } catch (Exception e) { + _LOG.fatal("Unexpected error", e); + } + System.exit(errorLevel); + } - Validator validator = - ValidatorFactory.getValidator(SchemaLanguage.XSD, - options); + public class Options { - try { - int num = 2; - long now = System.currentTimeMillis(); - for (int i = 0; i < num; i++) { - validator.validate(new FileInputStream(new File(args[0]))); + private SchemaLanguage _lang; + private File _xmlFile; + private boolean _cacheFiles; + private boolean _cacheObjects; + private boolean _allowMissing; + private int _repeat = 1; + private String _schema; + + private boolean _showVersion; + private boolean _showUsage; + + public Options(String[] args) throws ArgException { + + for (int i = 0; i < args.length; i++) { + if (args[i].startsWith("-")) { + if (args[i].equals("-cf") || args[i].equals("--cache-files")) { + _cacheFiles = true; + } else if (args[i].equals("-co") || args[i].equals("--cache-objects")) { + _cacheObjects = true; + } else if (args[i].equals("-am") || args[i].equals("--allow-missing")) { + _allowMissing=true; + } else if (args[i].startsWith("--repeat=")) { + String value = args[i].substring(9); + try { + _repeat = Integer.parseInt(value); + } catch (Exception e) { + throw new ArgException("must specify integer value for repeat option"); + } + } else if (args[i].startsWith("--schema=")) { + String value = args[i].substring(9); + if (!value.startsWith("/") && value.indexOf(":") != -1) { + _schema = value; // assume they gave uri + } else { + try { + _schema = new File(value).toURI().toString(); + } catch (Exception e) { + throw new RuntimeException("cannot get URI for local schema file: " + value, e); + } + } + } else if (args[i].equals("-h") || args[i].equals("--help")) { + _showUsage = true; + if (args.length > 1) { + throw new ArgException("option is exclusive: " + args[i]); + } + } else if (args[i].equals("-v") || args[i].equals("--version")) { + _showVersion = true; + if (args.length > 1) { + throw new ArgException("option is exclusive: " + args[i]); + } + } else { + throw new ArgException("unrecognized argument: " + args[i]); + } + } else { + System.out.println("Naked arg: " + args[i]); + if (_lang == null) { + try { + _lang = SchemaLanguage.forName(args[i]); + } catch (Exception e) { + throw new ArgException(e.getMessage()); + } + } else if (_xmlFile == null) { + _xmlFile = new File(args[i]); + } else { + throw new ArgException("Too many arguments"); + } + } + } - long dur = System.currentTimeMillis() - now; - long msPerDoc = dur / num; - System.out.println("Avg time/doc = " + msPerDoc); - System.out.println("OK"); - System.exit(0); - } catch (ValidationException e) { - System.out.println(e.getMessage()); - if (e.getCause() != null) { - System.out.println("Underlying error:"); - e.getCause().printStackTrace(); + + if (!_showVersion && !_showUsage && _xmlFile == null) { + throw new ArgException("Too few arguments"); } - System.exit(1); } + + public SchemaLanguage getLang() { + return _lang; + } + + public File getXMLFile() { + return _xmlFile; + } + + public boolean cacheFiles() { + return _cacheFiles; + } + + public boolean cacheObjects() { + return _cacheObjects; + } + + public boolean allowMissing() { + return _allowMissing; + } + + public int getRepeat() { + return _repeat; + } + + public String getSchema() { + return _schema; + } + + public boolean showVersion() { + return _showVersion; + } + + public boolean showUsage() { + return _showUsage; + } + } + public class ArgException extends Exception { + + public ArgException(String message) { + super(message); + } + + } + } Added: trunk/src/java/net/sf/bvalid/BValid.properties =================================================================== --- trunk/src/java/net/sf/bvalid/BValid.properties (rev 0) +++ trunk/src/java/net/sf/bvalid/BValid.properties 2006-05-01 06:57:49 UTC (rev 18) @@ -0,0 +1,2 @@ +bvalid.version = 1.0 +bvalid.buildDate = @buildDate@ Modified: trunk/src/java/net/sf/bvalid/catalog/FileSchemaIndex.java =================================================================== --- trunk/src/java/net/sf/bvalid/catalog/FileSchemaIndex.java 2006-04-28 05:07:57 UTC (rev 17) +++ trunk/src/java/net/sf/bvalid/catalog/FileSchemaIndex.java 2006-05-01 06:57:49 UTC (rev 18) @@ -120,6 +120,7 @@ protected static Map loadIndex(File indexFile) throws IOException { + if (!indexFile.exists()) return new HashMap(); InputStream in = new FileInputStream(indexFile); try { Modified: trunk/src/test/net/sf/bvalid/ValidatorFactoryTest.java =================================================================== --- trunk/src/test/net/sf/bvalid/ValidatorFactoryTest.java 2006-04-28 05:07:57 UTC (rev 17) +++ trunk/src/test/net/sf/bvalid/ValidatorFactoryTest.java 2006-05-01 06:57:49 UTC (rev 18) @@ -1,9 +1,11 @@ package net.sf.bvalid; +import java.util.*; + import junit.framework.TestCase; import junit.textui.TestRunner; -import net.sf.bvalid.locator.WebSchemaLocator; +import net.sf.bvalid.locator.URLSchemaLocator; public class ValidatorFactoryTest extends TestCase { @@ -17,25 +19,48 @@ //---------------------------------------------------------[ Test methods ] - public void testGetValidatorDefaultLocator() + public void testGetValidatorDefault() throws ValidatorException { - ValidatorFactory.getValidator(SchemaLanguage.XSD); + + ValidatorFactory.getValidator(SchemaLanguage.XSD, null); } - public void testGetValidatorSpecificLocator() + public void testGetValidatorCustom() throws ValidatorException { - ValidatorFactory.getValidator(SchemaLanguage.XSD, - new WebSchemaLocator()); + + ValidatorFactory.getValidator(SchemaLanguage.XSD, + new URLSchemaLocator(), + null); } - public void testGetValidatorNoFailOnMissingSchema() + public void testGetValidatorCustomWithGoodOptions() throws ValidatorException { - ValidatorFactory.getValidator(SchemaLanguage.XSD, - new WebSchemaLocator(), - false); + + Map options = new HashMap(); + options.put(ValidatorOption.CACHE_PARSED_GRAMMARS, "false"); + ValidatorFactory.getValidator(SchemaLanguage.XSD, + new URLSchemaLocator(), + options); } + public void testGetValidatorCustomWithBadOptions() + throws ValidatorException { + + Map options = new HashMap(); + options.put(ValidatorOption.CACHE_PARSED_GRAMMARS, "faults"); + boolean threwException = false; + try { + ValidatorFactory.getValidator(SchemaLanguage.XSD, + new URLSchemaLocator(), + options); + } catch (ValidatorException e) { + threwException = true; + } + assertEquals("Should have thrown exception due to bad option", true, threwException); + } + public static void main(String[] args) { + TestRunner.run(ValidatorFactoryTest.class); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |