[Mulgara-svn] r622 - in branches/mgr-73: . KOWARI-MODIFICATIONS conf docs/oldSite docs/site-src/system docs/site-src/tutorial jxdata/iTQL/fulltext_queries jxdata/iTQL/having_queries jxdata/iTQL/standard_queries jxdata/iTQL/transitive jxdata/iTQL/walk src/jar src/jar/ant-task/java/org/mulgara/ant/task/itql src/jar/ant-task/java/org/mulgara/ant/task/rdf src/jar/client-jrdf/java/org/mulgara/client/jrdf/test src/jar/client-jrdf/java/org/mulgara/client/jrdf/util src/jar/config src/jar/connection src/jar/connection/java/org/mulgara/connection src/jar/driver/java/org/mulgara/server/driver src/jar/itql src/jar/itql/java/org/mulgara/itql src/jar/itql/sablecc src/jar/jrdf/java/org/mulgara/jrdf src/jar/krule/java/org/mulgara/krule src/jar/parser src/jar/query src/jar/query/java/org/mulgara src/jar/query/java/org/mulgara/connection src/jar/query/java/org/mulgara/parser src/jar/query/java/org/mulgara/query src/jar/query/java/org/mulgara/query/operation src/jar/query/java/org/mulgara/query/rdf src/jar/query/java/org/mulgara/server src/jar/resolver/java/org/mulgara/resolver src/jar/resolver-distributed/java/org/mulgara/resolver/distributed src/jar/resolver-distributed/java/org/mulgara/resolver/distributed/remote src/jar/resolver-filesystem/java/org/mulgara/resolver/filesystem src/jar/resolver-gis/java/org/mulgara/resolver/gis src/jar/resolver-lucene/java/org/mulgara/resolver/lucene src/jar/resolver-memory/java/org/mulgara/resolver/memory src/jar/resolver-nodetype/java/org/mulgara/resolver/nodetype src/jar/resolver-prefix/java/org/mulgara/resolver/prefix src/jar/resolver-relational/java/org/mulgara/resolver/relational src/jar/resolver-spi/java/org/mulgara/resolver/spi src/jar/resolver-store/java/org/mulgara/resolver/store src/jar/resolver-test/java/org/mulgara/resolver/test src/jar/resolver-view/java/org/mulgara/resolver/view src/jar/resolver-xsd/java/org/mulgara/resolver/xsd src/jar/server/java/org/mulgara/server src/jar/server-rmi/java/org/mulgara/server/rmi src/jar/sofa/java/org/mulgara/sofa/example src/jar/tuples/java/org/mulgara/store/tuples src/jar/util/java/org/mulgara/util

andrae at mulgara.org andrae at mulgara.org
Tue Jan 22 02:18:10 UTC 2008


Author: andrae
Date: 2008-01-13 23:33:14 -0800 (Sun, 13 Jan 2008)
New Revision: 622

Added:
   branches/mgr-73/KOWARI-MODIFICATIONS/mods-mulgara-1.1.1.txt
   branches/mgr-73/conf/log4j-tql.xml
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Aliasing.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CommandSplitter.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlUtil.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/SableCCInterpreter.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlAutoInterpreter.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlCommandSplitter.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlInterpreter.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSession.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSessionUI.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/URIUtil.java
   branches/mgr-73/src/jar/parser/
   branches/mgr-73/src/jar/parser/build.xml
   branches/mgr-73/src/jar/parser/java/
   branches/mgr-73/src/jar/parser/parser-build.properties
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/Connection.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionException.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/DummyConnection.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/SessionConnection.java
   branches/mgr-73/src/jar/query/java/org/mulgara/parser/
   branches/mgr-73/src/jar/query/java/org/mulgara/parser/Interpreter.java
   branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java
   branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFilteredOperation.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/SelectElement.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/AddAlias.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Backup.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Command.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Commit.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DataTx.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Deletion.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DropGraph.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Help.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Insertion.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Load.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Modification.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/NullOp.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Quit.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Restore.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Rollback.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ServerCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetAutoCommit.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetTime.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetUser.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/TransactionCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/TxOp.java
   branches/mgr-73/src/jar/util/java/org/mulgara/util/Reflect.java
   branches/mgr-73/src/jar/util/java/org/mulgara/util/Tester.java
   branches/mgr-73/src/jar/util/java/org/mulgara/util/Tester2.java
Removed:
   branches/mgr-73/conf/log4j-itql.xml
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnection.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnectionUnitTest.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/InvalidQuerySyntaxException.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlConnection.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilder.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilderUnitTest.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MockBadSession.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnection.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionException.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactory.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactoryUnitTest.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/QueryBuilder.java
   branches/mgr-73/src/jar/connection/java/org/mulgara/connection/param/
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java
   branches/mgr-73/src/jar/parser/build.xml
   branches/mgr-73/src/jar/parser/java/
   branches/mgr-73/src/jar/parser/parser-build.properties
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/Connection.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionException.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/DummyConnection.java
   branches/mgr-73/src/jar/query/java/org/mulgara/connection/SessionConnection.java
   branches/mgr-73/src/jar/query/java/org/mulgara/parser/Interpreter.java
   branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java
   branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/AddAlias.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Backup.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Command.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Commit.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DataTx.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Deletion.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DropGraph.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Help.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Insertion.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Load.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Modification.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/NullOp.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Quit.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Restore.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Rollback.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ServerCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetAutoCommit.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetTime.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/SetUser.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/TransactionCommand.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/TxOp.java
Modified:
   branches/mgr-73/.classpath
   branches/mgr-73/build.properties
   branches/mgr-73/build.xml
   branches/mgr-73/common.properties
   branches/mgr-73/docs/oldSite/krule.htm
   branches/mgr-73/docs/site-src/system/itqlbean.html
   branches/mgr-73/docs/site-src/tutorial/krule.html
   branches/mgr-73/jxdata/iTQL/fulltext_queries/drop1.txt
   branches/mgr-73/jxdata/iTQL/fulltext_queries/test.jxu
   branches/mgr-73/jxdata/iTQL/having_queries/queryResult10.txt
   branches/mgr-73/jxdata/iTQL/having_queries/queryResult15-2.txt
   branches/mgr-73/jxdata/iTQL/having_queries/queryResult15.txt
   branches/mgr-73/jxdata/iTQL/standard_queries/queryResult18.txt
   branches/mgr-73/jxdata/iTQL/standard_queries/queryResult19.txt
   branches/mgr-73/jxdata/iTQL/standard_queries/queryResult3.txt
   branches/mgr-73/jxdata/iTQL/standard_queries/queryResult4.txt
   branches/mgr-73/jxdata/iTQL/transitive/result13.txt
   branches/mgr-73/jxdata/iTQL/transitive/result14.txt
   branches/mgr-73/jxdata/iTQL/walk/queryResult7.txt
   branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommand.java
   branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommandUnitTest.java
   branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoad.java
   branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadLog.java
   branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadUnitTest.java
   branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/test/ClientGraphUnitTest.java
   branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java
   branches/mgr-73/src/jar/config/build.xml
   branches/mgr-73/src/jar/connection/build.xml
   branches/mgr-73/src/jar/driver/java/org/mulgara/server/driver/SessionFactoryFinder.java
   branches/mgr-73/src/jar/itql/build.xml
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Collaborator.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CollaboratorUnitTest.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredListBuilder.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredicate.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ConstraintExpressionBuilder.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/HelpPrinter.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBean.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ModelExpressionBuilder.java
   branches/mgr-73/src/jar/itql/java/org/mulgara/itql/VariableBuilder.java
   branches/mgr-73/src/jar/itql/sablecc/itql.grammar
   branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFGraphUnitTest.java
   branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFLocalGraphUnitTest.java
   branches/mgr-73/src/jar/krule/java/org/mulgara/krule/KruleLoader.java
   branches/mgr-73/src/jar/krule/java/org/mulgara/krule/QueryStruct.java
   branches/mgr-73/src/jar/krule/java/org/mulgara/krule/RuleStructure.java
   branches/mgr-73/src/jar/query/build.xml
   branches/mgr-73/src/jar/query/java/org/mulgara/query/AbstractConstraintExpression.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/AggregateFunction.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstantValue.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/Constraint.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintConjunction.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDifference.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDisjunction.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintExpression.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFalse.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintHaving.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintImpl.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintIs.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNegation.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNotOccurs.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccurs.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursLessThan.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursMoreThan.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOperation.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintTrue.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelExpression.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelLiteral.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelOperation.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelResource.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/Query.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/QueryUnitTest.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/SingleTransitiveConstraint.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/SpecialPredicates.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/TransitiveConstraint.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/Variable.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/WalkConstraint.java
   branches/mgr-73/src/jar/query/java/org/mulgara/query/rdf/Mulgara.java
   branches/mgr-73/src/jar/query/java/org/mulgara/server/Session.java
   branches/mgr-73/src/jar/query/java/org/mulgara/server/SessionFactoryFactory.java
   branches/mgr-73/src/jar/resolver-distributed/java/org/mulgara/resolver/distributed/NetworkDelegator.java
   branches/mgr-73/src/jar/resolver-distributed/java/org/mulgara/resolver/distributed/remote/StatementSetFactory.java
   branches/mgr-73/src/jar/resolver-filesystem/java/org/mulgara/resolver/filesystem/FileSystemResolverFactory.java
   branches/mgr-73/src/jar/resolver-gis/java/org/mulgara/resolver/gis/WritableGISResolver.java
   branches/mgr-73/src/jar/resolver-lucene/java/org/mulgara/resolver/lucene/LuceneResolverFactory.java
   branches/mgr-73/src/jar/resolver-memory/java/org/mulgara/resolver/memory/MemoryResolution.java
   branches/mgr-73/src/jar/resolver-memory/java/org/mulgara/resolver/memory/MemoryResolver.java
   branches/mgr-73/src/jar/resolver-memory/java/org/mulgara/resolver/memory/MemoryResolverFactory.java
   branches/mgr-73/src/jar/resolver-nodetype/java/org/mulgara/resolver/nodetype/NodeTypeResolverFactory.java
   branches/mgr-73/src/jar/resolver-prefix/java/org/mulgara/resolver/prefix/PrefixResolverFactory.java
   branches/mgr-73/src/jar/resolver-relational/java/org/mulgara/resolver/relational/RelationalConstraint.java
   branches/mgr-73/src/jar/resolver-relational/java/org/mulgara/resolver/relational/RelationalConstraintDescriptor.java
   branches/mgr-73/src/jar/resolver-relational/java/org/mulgara/resolver/relational/RelationalResolverFactory.java
   branches/mgr-73/src/jar/resolver-relational/java/org/mulgara/resolver/relational/RelationalResolverUnitTest.java
   branches/mgr-73/src/jar/resolver-spi/java/org/mulgara/resolver/spi/ConjunctiveTransformer.java
   branches/mgr-73/src/jar/resolver-spi/java/org/mulgara/resolver/spi/ConjunctiveTransformerUnitTest.java
   branches/mgr-73/src/jar/resolver-spi/java/org/mulgara/resolver/spi/ConstraintBindingHandler.java
   branches/mgr-73/src/jar/resolver-spi/java/org/mulgara/resolver/spi/QueryEvaluationContext.java
   branches/mgr-73/src/jar/resolver-spi/java/org/mulgara/resolver/spi/ResolverFactoryInitializer.java
   branches/mgr-73/src/jar/resolver-spi/java/org/mulgara/resolver/spi/TripleSetWrapperStatements.java
   branches/mgr-73/src/jar/resolver-store/java/org/mulgara/resolver/store/StatementStoreResolverFactory.java
   branches/mgr-73/src/jar/resolver-test/java/org/mulgara/resolver/test/TestConstraint.java
   branches/mgr-73/src/jar/resolver-test/java/org/mulgara/resolver/test/TestResolverFactory.java
   branches/mgr-73/src/jar/resolver-test/java/org/mulgara/resolver/test/TestResolverUnitTest.java
   branches/mgr-73/src/jar/resolver-view/java/org/mulgara/resolver/view/ViewResolverFactory.java
   branches/mgr-73/src/jar/resolver-view/java/org/mulgara/resolver/view/ViewResolverUnitTest.java
   branches/mgr-73/src/jar/resolver-xsd/java/org/mulgara/resolver/xsd/IntervalConstraint.java
   branches/mgr-73/src/jar/resolver-xsd/java/org/mulgara/resolver/xsd/IntervalTransformationUnitTest.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/AdvDatabaseSessionUnitTest.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/AppendAggregateTuples.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/BasicDatabaseSessionUnitTest.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/CacheResolver.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/CacheResolverFactory.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/ConstraintOperations.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/Database.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/DatabaseMetadataImpl.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/DatabaseOperationContext.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/DatabaseSession.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/DatabaseSessionListQueryUnitTest.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/DatabaseSessionUnitTest.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/LocalJRDFDatabaseSession.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/LocalQueryResolver.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/ModelExistsOperation.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/ModifyModelOperation.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransaction.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/OperationContext.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/QueryOperation.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/SubqueryAnswer.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/SubqueryAnswerUnitTest.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/TestDef.java
   branches/mgr-73/src/jar/resolver/java/org/mulgara/resolver/XADatabaseSessionUnitTest.java
   branches/mgr-73/src/jar/server-rmi/java/org/mulgara/server/rmi/RemoteSessionFactoryImpl.java
   branches/mgr-73/src/jar/server-rmi/java/org/mulgara/server/rmi/RemoteSessionWrapperSession.java
   branches/mgr-73/src/jar/server-rmi/java/org/mulgara/server/rmi/RmiSessionFactory.java
   branches/mgr-73/src/jar/server/java/org/mulgara/server/ServerInfo.java
   branches/mgr-73/src/jar/sofa/java/org/mulgara/sofa/example/CameraPhoneOntologyApp.java
   branches/mgr-73/src/jar/tuples/java/org/mulgara/store/tuples/AbstractTuples.java
   branches/mgr-73/src/jar/tuples/java/org/mulgara/store/tuples/Tuples.java
   branches/mgr-73/src/jar/util/java/org/mulgara/util/NVPair.java
   branches/mgr-73/src/jar/util/java/org/mulgara/util/StringUtil.java
Log:
refs #73
sync's branch with trunk
merge -r 479:619 trunk/ .

Also improves the use of generics in Session which caused a problem with the
merge.  insert/delete now take <? extends Triple> instead of <Triple>, and the
Query constructor now takes List<? extends SelectElement> instead of
List<Object>.

Note: This commit is untested, will test shortly.



Modified: branches/mgr-73/.classpath
===================================================================
--- branches/mgr-73/.classpath	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/.classpath	2008-01-14 07:33:14 UTC (rev 622)
@@ -59,6 +59,7 @@
 	<classpathentry kind="src" path="src/jar/tuples-hybrid/java"/>
 	<classpathentry kind="src" path="src/jar/util/java"/>
 	<classpathentry kind="src" path="src/jar/util-xa/java"/>
+	<classpathentry kind="src" path="src/jar/parser/java"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
 	<classpathentry kind="lib" path="lib/xom-1.0d21.jar"/>
 	<classpathentry kind="lib" path="lib/xmlParserAPIs.jar"/>

Copied: branches/mgr-73/KOWARI-MODIFICATIONS/mods-mulgara-1.1.1.txt (from rev 619, trunk/KOWARI-MODIFICATIONS/mods-mulgara-1.1.1.txt)
===================================================================
--- branches/mgr-73/KOWARI-MODIFICATIONS/mods-mulgara-1.1.1.txt	                        (rev 0)
+++ branches/mgr-73/KOWARI-MODIFICATIONS/mods-mulgara-1.1.1.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,246 @@
+revision 557
+U   trunk/docs/oldSite/krule.htm
+U   trunk/docs/site-src/tutorial/krule.html
+pag
+2007-11-15 14:39:27 -0600 (Thu, 15 Nov 2007)
+73
+removed version numbers from the docs so that they don't fall out of date
+
+revision 556
+U   trunk/src/jar/config/build.xml
+U   trunk/src/jar/itql/build.xml
+pag
+2007-11-15 14:38:43 -0600 (Thu, 15 Nov 2007)
+69
+some minor dependency fixes to make building a little more consistent
+
+revision 464
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransaction.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransactionManager.java
+andrae
+2007-10-10 01:01:19 -0500 (Wed, 10 Oct 2007)
+130
+svn merge -r 426:430 ../branches/mgr-70
+
+Resolves mgr-70 - Using a database-session in multiple threads can deadlock the
+server.
+
+
+
+revision 463
+U   trunk/src/jar/query/java/org/mulgara/query/ModelOperation.java
+pag
+2007-10-05 14:02:51 -0500 (Fri, 05 Oct 2007)
+34
+Inverted test in the equals method
+
+revision 452
+U   trunk/src/jar/tuples-hybrid/java/org/mulgara/store/xa/HybridTuples.java
+pag
+2007-09-25 22:37:33 -0500 (Tue, 25 Sep 2007)
+107
+trivial update to call the correct delete method for a blockfile, rather than accessing the object directly
+
+revision 451
+U   trunk/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java
+pag
+2007-09-25 22:34:53 -0500 (Tue, 25 Sep 2007)
+96
+Fixed a bug where ending a transaction as the final answer would show an error in the client log
+
+revision 443
+U   trunk/src/jar/content-rdfxml/java/org/mulgara/content/rdfxml/writer/RDFXMLWriter.java
+ronald
+2007-09-19 05:30:55 -0500 (Wed, 19 Sep 2007)
+54
+Another continuation of r389: more closing of tuples.
+
+
+revision 442
+U   trunk/src/jar/content-rdfxml/java/org/mulgara/content/rdfxml/writer/TestStatementsComparator.java
+ronald
+2007-09-19 05:29:30 -0500 (Wed, 19 Sep 2007)
+25
+Fix use of wrong tuples.
+
+
+revision 441
+U   trunk/src/jar/resolver-relational/java/org/mulgara/resolver/relational/RelationalResolution.java
+U   trunk/src/jar/resolver-relational/java/org/mulgara/resolver/relational/d2rq/Definition.java
+ronald
+2007-09-19 04:39:47 -0500 (Wed, 19 Sep 2007)
+84
+Fixes some more unclosed-tuples leaks. This is a continuation of the fixes in
+r389.
+
+
+revision 440
+U   trunk/src/jar/tuples/java/org/mulgara/store/tuples/TuplesOperations.java
+ronald
+2007-09-19 04:37:15 -0500 (Wed, 19 Sep 2007)
+85
+Fix duplicate close() when UnboundJoin's are involved. This bug got exposed
+by r389.
+
+
+revision 431
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/ConstraintOperations.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/DatabaseOperationContext.java
+A   trunk/src/jar/resolver/java/org/mulgara/resolver/DefaultConstraintHandlers.java
+D   trunk/src/jar/resolver/java/org/mulgara/resolver/LocalQuery.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/LocalQueryResolver.java
+andrae
+2007-09-13 00:09:28 -0500 (Thu, 13 Sep 2007)
+188
+svn  merge -r 422:424 ../branches/mgr-69/
+
+For some reason the previous merge missed revisions 423 and 424 - which delete
+LocalQuery and complete the refactorings associated with mgr-69.
+
+
+
+revision 429
+U   trunk/src/jar/query/java/org/mulgara/query/Query.java
+andrae
+2007-09-12 00:17:42 -0500 (Wed, 12 Sep 2007)
+64
+Opps sorry about that, left some debugging info in by mistake.
+
+
+
+revision 425
+U   trunk/src/jar/query/java/org/mulgara/query/ModelExpression.java
+U   trunk/src/jar/query/java/org/mulgara/query/ModelIntersection.java
+U   trunk/src/jar/query/java/org/mulgara/query/ModelLiteral.java
+U   trunk/src/jar/query/java/org/mulgara/query/ModelOperation.java
+U   trunk/src/jar/query/java/org/mulgara/query/ModelPartition.java
+U   trunk/src/jar/query/java/org/mulgara/query/ModelResource.java
+U   trunk/src/jar/query/java/org/mulgara/query/ModelUnion.java
+U   trunk/src/jar/query/java/org/mulgara/query/Query.java
+D   trunk/src/jar/query/java/org/mulgara/query/Transformable.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/AppendAggregateTuples.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/Database.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/DatabaseOperationContext.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/LocalQuery.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/LocalQueryResolver.java
+A   trunk/src/jar/resolver/java/org/mulgara/resolver/MutableLocalQueryImpl.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/SubqueryAnswer.java
+andrae
+2007-09-11 07:33:31 -0500 (Tue, 11 Sep 2007)
+141
+svn merge -r408:COMMITTED ../branches/mgr-69/
+
+Refactor to eliminate LocalQuery and provide a single path for simple constraint
+resolution.
+
+
+
+revision 389
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/LocalQueryResolver.java
+U   trunk/src/jar/tuples/java/org/mulgara/store/tuples/TuplesOperations.java
+ronald
+2007-08-28 20:21:25 -0500 (Tue, 28 Aug 2007)
+314
+Fix file-descriptor leak: close tuples after use. TuplesOperations methods such
+as append(), join(), and subtract() make copies of the input tuples, so those
+inputs need to be explicitly closed. The missing closes were causing a file
+leak (and eventually a too-many-open-files error) in materialized HybridTuples.
+
+
+revision 388
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/ModifyModelOperation.java
+ronald
+2007-08-28 20:16:15 -0500 (Tue, 28 Aug 2007)
+140
+Improve fix in rev 217: only need the writable string pool for insert/select,
+not for delete/select (i.e. don't "create" values on delete).
+
+
+revision 375
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransaction.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransactionManager.java
+andrae
+2007-08-24 01:49:41 -0500 (Fri, 24 Aug 2007)
+256
+Reviewed ronald's fix to the transaction manager;
+Extracted a one line function to document the intent better;
+Added two lines of cleanup to the transaction abort cascade to allow for the
+implicitRollback control flow to now be truncated by an exception.
+
+
+
+revision 345
+U   trunk/.classpath
+U   trunk/build.properties
+U   trunk/build.xml
+U   trunk/common.xml
+U   trunk/jxdata/iTQL/data_types/dateTime/queryResult17.txt
+U   trunk/jxdata/iTQL/data_types/dateTime/queryResult18.txt
+U   trunk/jxdata/iTQL/data_types/dateTime/test.jxu
+A   trunk/jxdata/iTQL/having_queries/queryResult15-2.txt
+U   trunk/jxdata/iTQL/having_queries/test.jxu
+A   trunk/lib/commons-codec-1.3.jar
+D   trunk/lib/commons-httpclient-2.0.2.jar
+A   trunk/lib/commons-httpclient-3.0.1.jar
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/StreamContent.java
+U   trunk/src/jar/resolver-file/java/org/mulgara/resolver/file/FileContent.java
+U   trunk/src/jar/resolver-http/java/org/mulgara/resolver/http/HttpContent.java
+U   trunk/src/jar/resolver-http/java/org/mulgara/resolver/http/HttpContentUnitTest.java
+U   trunk/src/jar/resolver-http/java/org/mulgara/resolver/http/HttpResolver.java
+U   trunk/src/jar/resolver-http/java/org/mulgara/resolver/http/HttpResolverFactory.java
+U   trunk/src/jar/resolver-jar/java/org/mulgara/resolver/jar/JarContent.java
+U   trunk/src/jar/resolver-spi/java/org/mulgara/content/Content.java
+A   trunk/src/jar/util/java/java/
+D   trunk/src/jar/util/java/java/sql/
+A   trunk/src/jar/util/java/java/sql/
+D   trunk/src/jar/util/java/java/sql/NClob.java
+A   trunk/src/jar/util/java/java/sql/NClob.java
+D   trunk/src/jar/util/java/java/sql/RowId.java
+A   trunk/src/jar/util/java/java/sql/RowId.java
+D   trunk/src/jar/util/java/java/sql/SQLXML.java
+A   trunk/src/jar/util/java/java/sql/SQLXML.java
+U   trunk/src/jar/util/java/org/mulgara/util/ResultSetMetaDataImpl.java
+U   trunk/src/jar/util/java/org/mulgara/util/TestResultSet.java
+pag
+2007-08-08 23:09:07 -0500 (Wed, 08 Aug 2007)
+122
+Merged Java 1.6 compatibility into the trunk on r318:344.  Still some failing tests, but this is a problems with the tests
+
+revision 333
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransaction.java
+ronald
+2007-08-04 17:19:26 -0500 (Sat, 04 Aug 2007)
+302
+Fix error handling in implicit rollback. Since any error here will lead to
+abortTransaction() being invoked, clearing the manager in the error case will
+lead to a NPE in abortTransaction(). Furthermore, since abortTransaction()
+cleans everything up it seems better to leave the error handling to that.
+
+
+revision 332
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/AdvDatabaseSessionUnitTest.java
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransactionManager.java
+ronald
+2007-08-04 16:57:52 -0500 (Sat, 04 Aug 2007)
+177
+Fix write-lock acquisition bug and created test cases for it. The logic error
+was causing a second transaction to steal the write-lock instead of waiting
+for it to be released.
+
+
+revision 331
+U   trunk/src/jar/resolver/java/org/mulgara/resolver/MulgaraTransactionManager.java
+ronald
+2007-08-04 16:54:50 -0500 (Sat, 04 Aug 2007)
+148
+Invert logic of writeLockReserved() to better match the method name. At least
+I found the original confusing it made the locking bug harder to see.
+
+
+revision 326
+U   trunk/docs/site-src/index.html
+pag
+2007-07-28 10:18:22 -0500 (Sat, 28 Jul 2007)
+72
+Fixed the version number in the doc.  This should be updated dynamically
+

Modified: branches/mgr-73/build.properties
===================================================================
--- branches/mgr-73/build.properties	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/build.properties	2008-01-14 07:33:14 UTC (rev 622)
@@ -74,6 +74,7 @@
 # Executable JARs for distribution
 driver.jar        = driver-${mulgara-version}.jar
 itql.jar          = itql-${mulgara-version}.jar
+parser.jar        = parser-${mulgara-version}.jar
 mulgara.jar        = mulgara-${mulgara-version}.jar
 mulgara-lite.jar   = mulgara-lite-${mulgara-version}.jar
 mulgara-http.jar   = mulgara-http-${mulgara-version}.jar

Modified: branches/mgr-73/build.xml
===================================================================
--- branches/mgr-73/build.xml	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/build.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -556,7 +556,7 @@
                        ${axis.jar}, ${commons-discovery.jar},
                        ${jaxrpc.jar}, ${wsdl4j.jar}"/>
       <zipfileset dir="${bin.dir}" prefix="lib" includes="
-          ${query.jar}, ${driver.jar}, ${itql.jar}, ${rules.jar}, ${rmi.jar},
+        ${query.jar}, ${driver.jar}, ${itql.jar}, ${rules.jar}, ${rmi.jar},
           ${server.jar}, ${server-beep.jar}, ${server-rmi.jar},
           ${util.jar}, ${config.jar}, ${descriptor.jar}, ${server-local.jar},
           ${resolver.jar}, ${resolver-spi.jar}, ${resolver-filesystem.jar},
@@ -1399,7 +1399,7 @@
       <lib dir="${lib.dir}" includes="log4j-core-*.jar, icu4j.jar, jena-*.jar, antlr*.jar, beepcore-*.jar,
           lucene*.jar, apache-soap-*.jar, ${jrdf.jar}, ${date-utils.jar}, ${commons-logging.jar}"/>
       <lib dir="${bin.dir}" includes="${query.jar},
-          ${driver.jar}, ${itql.jar}, ${rules.jar}, ${rmi.jar},
+        ${driver.jar}, ${itql.jar}, ${rules.jar}, ${rmi.jar},
           ${server.jar}, ${server-beep.jar}, ${server-rmi.jar},
           ${util.jar}, ${config.jar}"/>
       <lib dir="${dist.dir}" includes="expires.txt"/>

Modified: branches/mgr-73/common.properties
===================================================================
--- branches/mgr-73/common.properties	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/common.properties	2008-01-14 07:33:14 UTC (rev 622)
@@ -7,8 +7,8 @@
 # Product properties
 project        =mulgara
 description    =Mulgara Semantic Store
-mulgara-version=1.1.0
-year           =2001-2006
+mulgara-version=1.1.1
+year           =2001-2007
 default.build.label=${description} Version ${mulgara-version} (Build @@build@@)
 
 # Build properties

Deleted: branches/mgr-73/conf/log4j-itql.xml
===================================================================
--- branches/mgr-73/conf/log4j-itql.xml	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/conf/log4j-itql.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,26 +0,0 @@
-<?xml version="1.0"?>
-<!DOCTYPE log4j:configuration SYSTEM "http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/xml/doc-files/log4j.dtd">
-
-<!--
-Log4J configuration for the Mulgara Query Engine project.
--->
-
-<log4j:configuration>
-
-  <!-- Log to a file -->
-  <appender name="LOGFILE" class="org.apache.log4j.FileAppender">
-    <param name="File" value="itql.log"/>
-    <layout class="org.apache.log4j.PatternLayout">
-      <param name="ConversionPattern" value="%d %-5p [%t] %C{2} - %m%n"/>
-    </layout>
-  </appender>
-
-  <!-- (Insert category elements here) -->
-
-  <!-- Default is to log messages of "info" priority -->
-  <root>
-    <priority value="WARN"/>
-    <appender-ref ref="LOGFILE"/>
-  </root>
-
-</log4j:configuration>

Copied: branches/mgr-73/conf/log4j-tql.xml (from rev 619, trunk/conf/log4j-tql.xml)
===================================================================
--- branches/mgr-73/conf/log4j-tql.xml	                        (rev 0)
+++ branches/mgr-73/conf/log4j-tql.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE log4j:configuration SYSTEM "http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/xml/doc-files/log4j.dtd">
+
+<!--
+Log4J configuration for the Mulgara Query Engine project.
+-->
+
+<log4j:configuration>
+
+  <!-- Log to a file -->
+  <appender name="LOGFILE" class="org.apache.log4j.FileAppender">
+    <param name="File" value="itql.log"/>
+    <layout class="org.apache.log4j.PatternLayout">
+      <param name="ConversionPattern" value="%d %-5p [%t] %C{2} - %m%n"/>
+    </layout>
+  </appender>
+
+  <!-- (Insert category elements here) -->
+
+  <!-- Default is to log messages of "info" priority -->
+  <root>
+    <priority value="WARN"/>
+    <appender-ref ref="LOGFILE"/>
+  </root>
+
+</log4j:configuration>

Modified: branches/mgr-73/docs/oldSite/krule.htm
===================================================================
--- branches/mgr-73/docs/oldSite/krule.htm	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/docs/oldSite/krule.htm	2008-01-14 07:33:14 UTC (rev 622)
@@ -73,7 +73,7 @@
 
           <h1 class="heading1">Mulgara Rules Engine (Krule) Users
           Guide</h1>
-          <p class="bodytext">Mulgara 1.0 includes a custom rules
+          <p class="bodytext">Mulgara includes a custom rules
           engine known as Krule (pronounced "cruel" by its lead
           developer).</p>
 
@@ -111,7 +111,7 @@
           Krule setup, you may have to also change the URLs
           embedded in the Krule rules files (called krule.owl and
           rdfs-krule.rdf, both of which are located in the
-          .../mulgaa-1.0/rules/ directory) and in the commands
+          .../mulgaa/rules/ directory) and in the commands
           given below.</p>
 
           <p class="bodytext">First, set up some handy aliases:</p>
@@ -143,7 +143,7 @@
           <p class="bodytext">Load the Krule ontology into your
           krule model. This ontology is used regardless of which
           rules are used. You will need to replace "@basedir@" with
-          the path to your Mulgara v1.0 source code
+          the path to your Mulgara source code
           installation:</p>
           <p class="commandtext">
 # Load the ontology for how the rules data fits together.
@@ -154,7 +154,7 @@
           <p class="bodytext">Load your rules into your krule
           model. In this case, we are loading the RDF Schema
           entailment rules which are provided in the file
-          .../mulgara-1.0/rules/rdfs-krule.rdf.</p>
+          .../mulgara/rules/rdfs-krule.rdf.</p>
           <p class="commandtext">
 # Load the rules data.
 load &lt;file:@basedir@/rules/rdfs-krule.rdf&gt;
@@ -168,7 +168,7 @@
 
           <p class="bodytext">Please note that the instructions in
           this section follow the file
-          .../mulgara-1.0/rules/example.itql, originally written by
+          .../mulgara/rules/example.itql, originally written by
           Paul Gearon.</p><a name="okrule2" id="okrule2">
 
           <h2 class="heading2">Using Krule</h2>
@@ -213,7 +213,7 @@
           <p class="commandtext">
 drop &lt;rmi://localhost/server1#input&gt;;
 create &lt;rmi://localhost/server1#input&gt;;
-load &lt;jar:file:/@basedir@/dist/mulgara-1.0.0.jar!/data/w3c-news.rss&gt;
+load &lt;jar:file:/@basedir@/dist/mulgara-<em>x.y.z</em>.jar!/data/w3c-news.rss&gt;
      into &lt;rmi://localhost/server1#input&gt;;
 </p>
 
@@ -302,13 +302,13 @@
 
           <p class="bodytext">Information for developers
           information may be found in the source under
-          .../mulgara-1.0/rules/RuleFormat.txt. That file includes a
+          .../mulgara/rules/RuleFormat.txt. That file includes a
           discussion on the format for rule definitions.</p>
 
           <p class="bodytext">A sample set of rules which implement
           RDF Schema (RDFS) entailments is provided in the source
           distribution in the file
-          .../mulgara-1.0/rules/rdfs-krule.rdf. You should review
+          .../mulgara/rules/rdfs-krule.rdf. You should review
           those rules to make sure you understand how they work
           before creating your own.</p>
 

Modified: branches/mgr-73/docs/site-src/system/itqlbean.html
===================================================================
--- branches/mgr-73/docs/site-src/system/itqlbean.html	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/docs/site-src/system/itqlbean.html	2008-01-14 07:33:14 UTC (rev 622)
@@ -79,8 +79,8 @@
 <br />
     System.out.println(&quot;Subject: &quot;+subject+&quot;, Predicate:&quot;+predicate+<br />
                        &quot;, Object: &quot;+object);<br />
-    answer.close();<br />
   }<br />
+  answer.close();<br />
 }<br />
 catch (Exception e) {<br />
   System.out.println(&quot;An Exception occurred: &quot;+e);<br />

Modified: branches/mgr-73/docs/site-src/tutorial/krule.html
===================================================================
--- branches/mgr-73/docs/site-src/tutorial/krule.html	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/docs/site-src/tutorial/krule.html	2008-01-14 07:33:14 UTC (rev 622)
@@ -41,7 +41,7 @@
 
           <h1>Mulgara Rules Engine (Krule) Users
           Guide</h1>
-          <p>Mulgara 1.0 includes a custom rules
+          <p>Mulgara includes a custom rules
           engine known as Krule (pronounced "cruel" by its lead
           developer).</p>
 
@@ -79,7 +79,7 @@
           Krule setup, you may have to also change the URLs
           embedded in the Krule rules files (called krule.owl and
           rdfs-krule.rdf, both of which are located in the
-          .../mulgaa-1.0/rules/ directory) and in the commands
+          .../mulgaa/rules/ directory) and in the commands
           given below.</p>
 
           <p>First, set up some handy aliases:</p>
@@ -111,7 +111,7 @@
           <p>Load the Krule ontology into your
           krule model. This ontology is used regardless of which
           rules are used. You will need to replace "@basedir@" with
-          the path to your Mulgara v1.0 source code
+          the path to your Mulgara source code
           installation:</p>
           <p class="commandtext">
 # Load the ontology for how the rules data fits together.
@@ -122,7 +122,7 @@
           <p>Load your rules into your krule
           model. In this case, we are loading the RDF Schema
           entailment rules which are provided in the file
-          .../mulgara-1.0/rules/rdfs-krule.rdf.</p>
+          .../mulgara/rules/rdfs-krule.rdf.</p>
           <p class="commandtext">
 # Load the rules data.
 load &lt;file:@basedir@/rules/rdfs-krule.rdf&gt;
@@ -136,7 +136,7 @@
 
           <p>Please note that the instructions in
           this section follow the file
-          .../mulgara-1.0/rules/example.itql, originally written by
+          .../mulgara/rules/example.itql, originally written by
           Paul Gearon.</p><a name="okrule2" id="okrule2"></a>
 
           <h2 class="">Using Krule</h2>
@@ -181,7 +181,7 @@
           <p class="commandtext">
 drop &lt;rmi://localhost/server1#input&gt;;
 create &lt;rmi://localhost/server1#input&gt;;
-load &lt;jar:file:/@basedir@/dist/mulgara-1.0.0.jar!/data/w3c-news.rss&gt;
+load &lt;jar:file:/@basedir@/dist/mulgara-<em>x.y.z</em>.jar!/data/w3c-news.rss&gt;
      into &lt;rmi://localhost/server1#input&gt;;
 </p>
 
@@ -270,13 +270,13 @@
 
           <p>Information for developers
           information may be found in the source under
-          .../mulgara-1.0/rules/RuleFormat.txt. That file includes a
+          .../mulgara/rules/RuleFormat.txt. That file includes a
           discussion on the format for rule definitions.</p>
 
           <p>A sample set of rules which implement
           RDF Schema (RDFS) entailments is provided in the source
           distribution in the file
-          .../mulgara-1.0/rules/rdfs-krule.rdf. You should review
+          .../mulgara/rules/rdfs-krule.rdf. You should review
           those rules to make sure you understand how they work
           before creating your own.</p>
 

Modified: branches/mgr-73/jxdata/iTQL/fulltext_queries/drop1.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/fulltext_queries/drop1.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/fulltext_queries/drop1.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,2 +1,2 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<answer xmlns="http://mulgara.org/tql#"><query><message>Successfully dropped model @server@#model1</message></query><query><message>Successfully dropped model @server@#fulltext</message></query><query><message>Successfully dropped model @server@#fulltext2</message></query><query><message>Successfully dropped model @server@#normal_zh</message></query><query><message>Successfully dropped model @server@#fulltext_zh</message></query><query><message>Successfully dropped model @server@#numbers_test</message></query><query><message></message></query></answer>
+<answer xmlns="http://mulgara.org/tql#"><query><message>Successfully dropped model @server@#model1</message></query><query><message>Successfully dropped model @server@#fulltext</message></query><query><message>Successfully dropped model @server@#fulltext2</message></query><query><message>Successfully dropped model @server@#normal_zh</message></query><query><message>Successfully dropped model @server@#fulltext_zh</message></query><query><message>Successfully dropped model @server@#numbers_test</message></query><query><message>Successfully dropped model @server@#numbers_fulltext</message></query></answer>

Modified: branches/mgr-73/jxdata/iTQL/fulltext_queries/test.jxu
===================================================================
--- branches/mgr-73/jxdata/iTQL/fulltext_queries/test.jxu	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/fulltext_queries/test.jxu	2008-01-14 07:33:14 UTC (rev 622)
@@ -312,7 +312,7 @@
            drop &lt;@server@#normal_zh&gt; ;
            drop &lt;@server@#fulltext_zh&gt; ;
            drop &lt;@server@#numbers_test&gt; ;
-           drop &lt;@server@#numbers; ;"/>
+           drop &lt;@server@#numbers_fulltext&gt; ;"/>
 
   <eval stepClass="org.mulgara.store.jxunit.QueryJX" />
   <ifEqual converse="true" file="drop1.txt" name="queryResult">

Modified: branches/mgr-73/jxdata/iTQL/having_queries/queryResult10.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/having_queries/queryResult10.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/having_queries/queryResult10.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,5 +1,4 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Query failed
-Caused by: (QueryException) Query failed
+ItqlInterpreter error - Query failed
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) Failed to resolve query
 Caused by: (QueryException) org.mulgara.query.TuplesException: No such variable $v in tuples [$s, $k0] (class org.mulgara.resolver.AppendAggregateTuples)

Modified: branches/mgr-73/jxdata/iTQL/having_queries/queryResult15-2.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/having_queries/queryResult15-2.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/having_queries/queryResult15-2.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,5 +1,4 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Query failed
-Caused by: (QueryException) Query failed
+ItqlInterpreter error - Query failed
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) Failed to resolve query
 Caused by: (QueryException) org.mulgara.query.TuplesException: No such variable $k0 in tuples [$v, $p, $s] (class org.mulgara.resolver.AppendAggregateTuples)

Modified: branches/mgr-73/jxdata/iTQL/having_queries/queryResult15.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/having_queries/queryResult15.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/having_queries/queryResult15.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,5 +1,4 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Query failed
-Caused by: (QueryException) Query failed
+ItqlInterpreter error - Query failed
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) Failed to resolve query
 Caused by: (QueryException) org.mulgara.query.TuplesException: No such variable $k0 in tuples [$p, $v, $s] (class org.mulgara.resolver.AppendAggregateTuples)

Modified: branches/mgr-73/jxdata/iTQL/standard_queries/queryResult18.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/standard_queries/queryResult18.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/standard_queries/queryResult18.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,5 +1,4 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Query failed
-Caused by: (QueryException) Query failed
+ItqlInterpreter error - Query failed
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) Error resolving [$s $p $o $_from] from mailto:foo at bar.com
 Caused by: (QueryException) Unable to extract hostname from: mailto:foo at bar.com

Modified: branches/mgr-73/jxdata/iTQL/standard_queries/queryResult19.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/standard_queries/queryResult19.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/standard_queries/queryResult19.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,4 +1,3 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Unable to reconnect to rmi://localhost/server2
-Caused by: (QueryException) Unable to reconnect to rmi://localhost/server2
-Caused by: (SessionFactoryFinderException) Cannot find server rmi://localhost/server2
-Caused by: (NameNotFoundException) server2
+ItqlInterpreter error - Unable to connect to a server
+Caused by: (SessionFactoryFinderException) Couldn't create session factory for rmi://localhost/server2
+Caused by: (ClassNotFoundException) org.mulgara.server.local.LocalSessionFactory

Modified: branches/mgr-73/jxdata/iTQL/standard_queries/queryResult3.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/standard_queries/queryResult3.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/standard_queries/queryResult3.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,5 +1,4 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Query failed
-Caused by: (QueryException) Query failed
+ItqlInterpreter error - Query failed
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) Error resolving [$pmid http://mulgara.org/mulgara/Document#subject "Birds" $_from] from @server@#badmodel
 Caused by: (QueryException) @server@#badmodel is not a Model

Modified: branches/mgr-73/jxdata/iTQL/standard_queries/queryResult4.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/standard_queries/queryResult4.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/standard_queries/queryResult4.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,2 +1 @@
-ItqlInterpreter error - java.lang.IllegalArgumentException: Failed to constrain all variables: $pmid2 not constrained in WHERE or GIVEN clauses
-Caused by: (IllegalArgumentException) Failed to constrain all variables: $pmid2 not constrained in WHERE or GIVEN clauses
+ItqlInterpreter error - Failed to constrain all variables: $pmid2 not constrained in WHERE or GIVEN clauses

Modified: branches/mgr-73/jxdata/iTQL/transitive/result13.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/transitive/result13.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/transitive/result13.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,4 +1,3 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Query failed
-Caused by: (QueryException) Query failed
+ItqlInterpreter error - Query failed
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) Predicate in transitive function, $p, currently must be bound to a value.

Modified: branches/mgr-73/jxdata/iTQL/transitive/result14.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/transitive/result14.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/transitive/result14.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,4 +1,3 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Query failed
-Caused by: (QueryException) Query failed
+ItqlInterpreter error - Query failed
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) Predicate in transitive function, $p, currently must be bound to a value.

Modified: branches/mgr-73/jxdata/iTQL/walk/queryResult7.txt
===================================================================
--- branches/mgr-73/jxdata/iTQL/walk/queryResult7.txt	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/jxdata/iTQL/walk/queryResult7.txt	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,5 +1,4 @@
-ItqlInterpreter error - org.mulgara.query.QueryException: Error getting information for answer
-Caused by: (QueryException) Error getting information for answer
+ItqlInterpreter error - Error getting information for answer
 Caused by: (QueryException) org.mulgara.query.TuplesException: Transaction error
 Caused by: (QueryException) org.mulgara.query.MulgaraTransactionException: Transaction rollback triggered
 Caused by: (QueryException) org.mulgara.query.TuplesException: Couldn't evaluate aggregate

Modified: branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommand.java
===================================================================
--- branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommand.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommand.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -29,7 +29,6 @@
 
 import java.io.*;
 import java.net.*;
-import java.sql.*;
 
 // Java
 import java.util.*;
@@ -44,9 +43,7 @@
 import org.apache.tools.ant.Task;
 import org.mulgara.itql.ItqlInterpreterBean;
 import org.mulgara.query.Answer;
-import org.mulgara.query.QueryException;
 import org.mulgara.query.TuplesException;
-import org.mulgara.server.Session;
 
 /**
  * An Ant Task to execute ITQL commands. <p>
@@ -78,12 +75,6 @@
  *
  * @author Ben Warren
  *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:57:31 $
- *
- * @maintenanceAuthor $Author: newmana $
- *
  * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
  *
  * @copyright &copy;2002 <a href="http://www.pisoftware.com/">Plugged In
@@ -93,146 +84,114 @@
  */
 public class ITQLCommand extends Task {
 
-  /**
-   * The logging catgory
-   */
+  /** The logging catgory */
   private final static Logger logger = Logger.getLogger(ITQLCommand.class);
 
-  /**
-   * Get line separator.
-   */
+  /** Get line separator. */
   private static final String eol = System.getProperty("line.separator");
 
-  /**
-   * Ignore errors
-   */
+  /** Ignore errors */
   protected boolean ignoreErrors = false;
 
-  /**
-   * The log4j XML config file
-   */
+  /** The log4j XML config file */
   protected File logConfig = null;
 
-  /**
-   * The queries to execute
-   */
-  protected List queryList = new ArrayList();
+  /** The queries to execute */
+  protected List<ITQLQuery> queryList = new ArrayList<ITQLQuery>();
 
-  /**
-   * The ITQL interpreter
-   */
+  /** The ITQL interpreter */
   protected ItqlInterpreterBean interpreter = null;
 
-  /**
-   * The number of files executed
-   */
+  /** The number of files executed */
   private int numExecuted = 0;
 
-  /**
-   * The number of errors
-   */
+  /** The number of errors */
   private int numErrors = 0;
 
   /**
    * Set if errors should be ignored (default is false).
-   *
    * @param ignore The new IgnoreErrors value
    */
   public void setIgnoreErrors(boolean ignore) {
-
     ignoreErrors = ignore;
   }
 
+
   /**
    * Set the log4j XML config file (Optional - if none specified, console
    * logging will be used).
-   *
    * @param config The log4j XML config file.
    */
   public void setLogconfig(File config) {
-
     logConfig = config;
   }
 
+
   /**
    * Get the number of files executed.
-   *
    * @return The number of files executed.
    */
   public int getNumExecuted() {
-
     return numExecuted;
   }
 
+
   /**
    * Get the number of errors that occurred.
-   *
    * @return The number of errors that occurred.
    */
   public int getNumErrors() {
-
     return numErrors;
   }
 
+
   /**
    * Initialise the task.
-   *
    * @throws BuildException on error.
    */
   public void init() throws BuildException {
-
     super.init();
   }
 
+
   /**
    * Add an ITQL query.
-   *
    * @param query The query to add.
    */
   public void addItqlquery(ITQLQuery query) {
-
     queryList.add(query);
   }
 
+
   /**
    * Executes the commands.
-   *
    * @throws BuildException on error.
    */
   public void execute() throws BuildException {
-
     try {
-
       log("Running with this config:" + eol + this.toString(), Project.MSG_DEBUG);
-
       setupLog();
 
-      if (logger.isDebugEnabled()) {
+      if (logger.isDebugEnabled()) logger.debug("Running with this config:" + eol + toString());
 
-        logger.debug("Running with this config:" + eol + this.toString());
-      }
-
       interpreter = new ItqlInterpreterBean();
 
       executeQueries();
-    }
-    finally {
 
+    } finally {
       if (interpreter != null) {
-
         try {
           interpreter.close();
-        }
-        finally {
+        } finally {
           interpreter = null;
         }
       }
     }
   }
 
+
   /**
    * Overrides Object.toString()
-   *
    * @return A string representing this task.
    */
   public String toString() {
@@ -245,50 +204,42 @@
     return buffer.toString();
   }
 
+
   /**
    * Setup the log if required.
-   *
    * @throws BuildException on error.
    */
   protected void setupLog() throws BuildException {
-
     // log4j logging
     if (logConfig != null) {
-
       try {
-
         DOMConfigurator.configure(logConfig.toURL());
-      }
-      catch (MalformedURLException me) {
-
+      } catch (MalformedURLException me) {
         throw new BuildException("Could not configure log4j!", me);
       }
-    }
-    else {
-
+    } else {
       BasicConfigurator.configure();
-
       // Disable debug
       LogManager.getLoggerRepository().setThreshold(Level.OFF);
     }
   }
 
+
   /**
    * Get the result of a query as a string;
-   *
    * @param query The query to execute.
    * @return The result of the query as a String or Exception or null if there
-   *      was no result.
+   *         was no result.
    * @throws BuildException if the result was of an unexpected type.
    */
   protected Object getQueryResult(String query) {
+    List<Object> list = interpreter.executeQueryToList(query, true);
 
-    List list = interpreter.executeQueryToList(query, true);
-
     if (list.size() > 0) {
 
       Object answer = list.get(0);
       try {
+        // close the rest of the list
         for (int i = 1; i < list.size(); i++) {
           Object a = list.get(i);
           if (a instanceof Answer) ((Answer)a).close();
@@ -298,13 +249,12 @@
       }
 
       return answer;
-    }
-    else {
-
+    } else {
       throw new BuildException("Did not get an answer for the query: " + query);
     }
   }
 
+
   /**
    * Executes the queries.
    *
@@ -313,30 +263,25 @@
   protected void executeQueries() throws BuildException {
 
     // Loop through the commands
-    for (Iterator iter = queryList.iterator(); iter.hasNext(); ) {
+    for (ITQLQuery itqlQuery: queryList) {
 
-      ITQLQuery itqlQuery = (ITQLQuery) iter.next();
       String query = itqlQuery.getQuery();
 
       // Is there a query?
       if (query != null) {
+        if (logger.isInfoEnabled()) logger.info("Executing query: " + query);
 
-        if (logger.isInfoEnabled()) {
-
-          logger.info("Executing query: " + query);
-        }
-
         log("Executing query: " + query, Project.MSG_INFO);
 
         // Do the query
-        Object object = getQueryResult(query);
+        Object queryResult = getQueryResult(query);
 
         numExecuted++;
 
-        // String
-        if (object instanceof String) {
+        // If result is a string
+        if (queryResult instanceof String) {
 
-          String string = (String) object;
+          String string = (String)queryResult;
 
           if (string.startsWith("Successfully") ||
               string.startsWith("Auto commit") ||
@@ -345,54 +290,37 @@
 
             log("Result message: " + string, Project.MSG_INFO);
 
-            if (logger.isInfoEnabled()) {
+            if (logger.isInfoEnabled()) logger.info("Result message: " + string);
+          } else {
 
-              logger.info("Result message: " + string);
-            }
-          }
-          else {
-
             numErrors++;
 
-            log("Exception executing query '" + query + "' : " + string,
-                Project.MSG_ERR);
-            logger.error("Exception executing query '" + query + "' : " +
-                string);
+            log("Exception executing query '" + query + "' : " + string, Project.MSG_ERR);
+            logger.error("Exception executing query '" + query + "' : " + string);
 
-            if (!ignoreErrors) {
-
-              break;
-            }
+            if (!ignoreErrors) break;
           }
-        }
+        } else if (queryResult instanceof Answer) {
+          // Result is an Answer
 
-        // Answer
-        else if (object instanceof Answer) {
+          Answer answer = (Answer) queryResult;
 
-          Answer answer = (Answer) object;
-
           try {
-
             if (!answer.isUnconstrained()) {
 
-              log("Result set contained " + answer.getRowCount() +
-                  " row(s).", Project.MSG_INFO);
+              log("Result set contained " + answer.getRowCount() + " row(s).", Project.MSG_INFO);
 
               if (logger.isInfoEnabled()) {
-
-                logger.info("Result set contained " +
-                    answer.getRowCount() + "rows.");
+                logger.info("Result set contained " + answer.getRowCount() + "rows.");
               }
-            }
-            else {
+            } else {
 
               log("Query result contained null result set.", Project.MSG_INFO);
               logger.info("Query result contained null result set.");
             }
 
             answer.close();
-          }
-          catch (TuplesException qe) {
+          } catch (TuplesException qe) {
 
             log("Exception getting result set: " + qe, Project.MSG_ERR);
 
@@ -401,42 +329,31 @@
               logger.error("Exception getting result set.", qe);
             }
           }
-        }
 
-        // Bad query
-        else if (object instanceof Exception) {
+        } else if (queryResult instanceof Exception) {
+          // Result indicates a bad query
 
-          Exception ex = (Exception) object;
+          Exception ex = (Exception) queryResult;
           StringWriter swriter = new StringWriter();
           PrintWriter pwriter = new PrintWriter(swriter);
           ex.printStackTrace(pwriter);
           numErrors++;
 
-          log("Exception executing query '" + query + "' : " + swriter,
-              Project.MSG_ERR);
-          logger.error("Exception executing query '" + query + "' : " +
-              swriter);
+          log("Exception executing query '" + query + "' : " + swriter, Project.MSG_ERR);
+          logger.error("Exception executing query '" + query + "' : " + swriter);
 
-          if (!ignoreErrors) {
-
-            break;
-          }
-        }
-        else {
-
+          if (!ignoreErrors) break;
+        } else {
           throw new BuildException("Unknown object returned from query: " +
-              object.getClass().getName());
+              queryResult.getClass().getName());
         }
-      }
-      else {
-
+      } else {
+        // query result was not a string, answer, or exception: therefore unknown
         throw new BuildException("A query was null!");
       }
     }
 
-    log("Executed " + numExecuted + " commands with " + numErrors + " errors.",
-        Project.MSG_INFO);
-    logger.info("Executed " + numExecuted + " commands with " + numErrors +
-        " errors.");
+    log("Executed " + numExecuted + " commands with " + numErrors + " errors.", Project.MSG_INFO);
+    logger.info("Executed " + numExecuted + " commands with " + numErrors + " errors.");
   }
 }

Modified: branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommandUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommandUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/itql/ITQLCommandUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -31,23 +31,16 @@
 import junit.framework.TestCase;
 import junit.framework.TestSuite;
 
-import java.io.*;
 import java.net.*;
-import java.sql.*;
 
 // Java
 import java.util.*;
 
 // Log4j
 import org.apache.log4j.*;
-import org.apache.tools.ant.BuildException;
 
 // Ant
 import org.apache.tools.ant.Project;
-import org.apache.tools.ant.Target;
-import org.apache.tools.ant.Task;
-import org.apache.tools.ant.types.FileSet;
-import org.apache.tools.ant.types.Path;
 import org.mulgara.itql.ItqlInterpreterBean;
 import org.mulgara.query.Answer;
 
@@ -58,75 +51,45 @@
  *
  * @author Ben Warren
  *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:57:32 $
- *
- * @maintenanceAuthor $Author: newmana $
- *
  * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
  *
- * @copyright &copy;2002 <a href="http://www.pisoftware.com/">Plugged In
- *      Software Pty Ltd</a>
+ * @copyright &copy;2002 <a href="http://www.pisoftware.com/">Plugged In Software Pty Ltd</a>
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
 public class ITQLCommandUnitTest extends TestCase {
 
-  /**
-   * Log category
-   */
+  /** Log category */
+  @SuppressWarnings("unused")
   private final static Logger log = Logger.getLogger(ITQLCommandUnitTest.class);
 
-  /**
-   * Description of the Field
-   */
+  /** Description of the Field */
   String RDF_TYPE_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
 
-  /**
-   * Description of the Field
-   */
+  /** Description of the Field */
   String MODEL_URI = "http://mulgara.org/mulgara#Model";
 
-  /**
-   * Description of the Field
-   */
+  /** Description of the Field */
   String JOURNAL_URI = "urn:medline:Journal";
 
-  /**
-   * Description of the Field
-   */
+  /** Description of the Field */
   ItqlInterpreterBean interpreter = null;
 
-  /**
-   * Description of the Field
-   */
-  String hostName = null;
-
-  /**
-   * Description of the Field
-   */
+  /** Description of the Field */
   String testModel = null;
 
-  /**
-   * Description of the Field
-   */
+  /** Description of the Field */
   ITQLCommand command = null;
 
   /**
-   * Description of the Field
-   */
-  String baseDir = System.getProperty("basedir");
-
-  /**
    * Public constructor.
    *
-   * @param name PARAMETER TO DO
-   * @throws Exception EXCEPTION TO DO
+   * @param name Name of the test
+   * @throws Exception Initialization was not possible.
    */
   public ITQLCommandUnitTest(String name) throws Exception {
     super(name);
-    hostName = InetAddress.getLocalHost().getCanonicalHostName();
+    String hostName = InetAddress.getLocalHost().getCanonicalHostName();
     testModel = "rmi://" + hostName + "/server1#itqlcommand-test-model";
   }
 
@@ -134,14 +97,12 @@
    * Builds a test suite.
    *
    * @return A test suite.
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception Unable to create the suite
    */
   public static TestSuite suite() throws Exception {
-
     TestSuite suite = new TestSuite();
     suite.addTest(new ITQLCommandUnitTest("testAbortOnErrors"));
     suite.addTest(new ITQLCommandUnitTest("testIgnoreErrors"));
-
     return suite;
   }
 
@@ -149,17 +110,9 @@
    * Runs the tests.
    *
    * @param args The args.
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception The tests would not run
    */
   public static void main(String[] args) throws Exception {
-
-    String baseDir = System.getProperty("basedir");
-
-    if (baseDir == null) {
-
-      throw new RuntimeException("Could not get the 'basedir' system property");
-    }
-
     BasicConfigurator.configure();
     junit.textui.TestRunner.run(suite());
   }
@@ -169,26 +122,24 @@
    *
    */
   public void setUp() throws Exception {
-
     interpreter = new ItqlInterpreterBean();
-    boolean exceptionOccurred = true;
     try {
       Project project = new Project();
       project.init();
       command = new ITQLCommand();
       command.init();
       command.setProject(project);
-
-      exceptionOccurred = false;
-    } finally {
-      if (exceptionOccurred) tearDown();
+    } catch (Exception e) {
+      log.error("Unable to set up the curren test", e);
+      e.printStackTrace();
+      tearDown();
     }
   }
 
   /**
    * Test presenting credentials.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception Generic failed test condition.
    */
   public void testAbortOnErrors() throws Exception {
 
@@ -202,13 +153,11 @@
 
     // Insert some data
     ITQLQuery query3 = new ITQLQuery();
-    query3.setQuery("insert <http://test> <http://data> 'Hello World' " +
-                    "into <" + testModel + "> ;");
+    query3.setQuery("insert <http://test> <http://data> 'Hello World' into <" + testModel + "> ;");
 
     // Query the data
     ITQLQuery query4 = new ITQLQuery();
-    query4.setQuery("select $s $p $o from <" + testModel +
-                    "> where $s $p $o ;");
+    query4.setQuery("select $s $p $o from <" + testModel + "> where $s $p $o ;");
 
     // Commit
     ITQLQuery query5 = new ITQLQuery();
@@ -220,8 +169,7 @@
 
     // Insert some more data
     ITQLQuery query7 = new ITQLQuery();
-    query7.setQuery("insert <http://more> <http://data> ':-)' " + "into <" +
-                    testModel + "> ;");
+    query7.setQuery("insert <http://more> <http://data> ':-)' " + "into <" + testModel + "> ;");
 
     // Set auto commit on
     ITQLQuery query8 = new ITQLQuery();
@@ -242,19 +190,13 @@
     assertEquals("Wrong number of errors", 1, command.getNumErrors());
 
     // Check number executed
-    assertEquals("Wrong number of commands executed", 6,
-                 command.getNumExecuted());
+    assertEquals("Wrong number of commands executed", 6, command.getNumExecuted());
 
     // Check for second lot of data
-    Answer answer =
-        (Answer) interpreter.executeQueryToList("select $o from <" + testModel +
-                                                 "> where $s $p $o;").get(0);
+    Answer answer = (Answer)interpreter.executeQueryToList("select $o from <" + testModel + "> where $s $p $o;").get(0);
 
-    if (answer.isUnconstrained()) {
+    if (answer.isUnconstrained()) fail("Result set was null");
 
-      fail("Result set was null");
-    }
-
     // There should be 1 row of data
     assertEquals("Wrong number of rows", 1, answer.getRowCount());
     answer.close();
@@ -263,7 +205,7 @@
   /**
    * Test presenting credentials.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception Generic failed test condition
    */
   public void testIgnoreErrors() throws Exception {
 
@@ -277,13 +219,11 @@
 
     // Insert some data
     ITQLQuery query3 = new ITQLQuery();
-    query3.setQuery("insert <http://test> <http://data> 'Hello World' " +
-                    "into <" + testModel + "> ;");
+    query3.setQuery("insert <http://test> <http://data> 'Hello World' into <" + testModel + "> ;");
 
     // Query the data
     ITQLQuery query4 = new ITQLQuery();
-    query4.setQuery("select $s $p $o from <" + testModel +
-                    "> where $s $p $o ;");
+    query4.setQuery("select $s $p $o from <" + testModel + "> where $s $p $o ;");
 
     // Commit
     ITQLQuery query5 = new ITQLQuery();
@@ -295,8 +235,7 @@
 
     // Insert some more data
     ITQLQuery query7 = new ITQLQuery();
-    query7.setQuery("insert <http://more> <http://data> ':-)' " + "into <" +
-                    testModel + "> ;");
+    query7.setQuery("insert <http://more> <http://data> ':-)' " + "into <" + testModel + "> ;");
 
     // Set auto commit on
     ITQLQuery query8 = new ITQLQuery();
@@ -317,19 +256,14 @@
     assertEquals("Wrong number of errors", 1, command.getNumErrors());
 
     // Check number executed
-    assertEquals("Wrong number of commands executed", 8,
-                 command.getNumExecuted());
+    assertEquals("Wrong number of commands executed", 8, command.getNumExecuted());
 
     // Check for second lot of data
-    List resultList = interpreter.executeQueryToList("select $o from <" + testModel +
-                                                 "> where $s $p $o;");
+    List<Object> resultList = interpreter.executeQueryToList("select $o from <" + testModel + "> where $s $p $o;");
     Answer answer = (Answer)resultList.get(0);
 
-    if (answer.isUnconstrained()) {
+    if (answer.isUnconstrained()) fail("Result set was null");
 
-      fail("Result set was null");
-    }
-
     // There should be 2 rows of data
     assertEquals("Wrong number of rows", 2, answer.getRowCount());
 

Modified: branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoad.java
===================================================================
--- branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoad.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoad.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -29,7 +29,6 @@
 
 import java.io.*;
 import java.net.*;
-import java.sql.*;
 
 // Java
 import java.util.*;
@@ -38,7 +37,6 @@
 import org.apache.log4j.*;
 import org.apache.log4j.xml.*;
 import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.DirectoryScanner;
 import org.apache.tools.ant.Project;
 
 // Ant
@@ -47,7 +45,6 @@
 import org.apache.tools.ant.types.Path;
 import org.mulgara.itql.ItqlInterpreterBean;
 import org.mulgara.query.Answer;
-import org.mulgara.query.QueryException;
 import org.mulgara.query.TuplesException;
 
 /**
@@ -124,109 +121,67 @@
   */
 public class RDFLoad extends Task {
 
-  /**
-   * The logging catgory *
-   */
+  /** The logging catgory */
   private final static Logger logger = Logger.getLogger(RDFLoad.class);
 
-  /**
-   * Get line separator.
-   */
+  /** Get line separator. */
   private static final String eol = System.getProperty("line.separator");
 
-  /**
-   * The file to log to.
-   */
+  /** The file to log to. */
   protected File logFile = null;
 
-  /**
-   * The URI of the model to load into.
-   */
+  /** The URI of the model to load into. */
   protected URI modelURI = null;
 
-  /**
-   * The security domain of server where the model resides.
-   */
+  /** The security domain of server where the model resides. */
   protected URI domainURI = null;
 
-  /**
-   * The username for the security domain.
-   */
+  /** The username for the security domain. */
   protected String username = null;
 
-  /**
-   * The password for the security domain.
-   */
+  /** The password for the security domain. */
   protected String password = null;
 
-  /**
-   * The RDF files to load
-   */
+  /** The RDF files to load */
   protected Path rdfPath = null;
 
-  /**
-   * The directory to load RDF from
-   */
+  /** The directory to load RDF from */
   protected File rdfDir = null;
 
-  /**
-   * Drop the model before loading
-   */
+  /** Drop the model before loading */
   protected boolean dropModel = false;
 
-  /**
-   * The maximum number of permissable errors before aborting the load
-   */
+  /** The maximum number of permissable errors before aborting the load */
   protected int maxErrors = 0;
 
-  /**
-   * Ignore errors
-   */
+  /** Ignore errors */
   protected boolean ignoreErrors = false;
 
-  /**
-   * The number of files to load in each transaction
-   */
+  /** The number of files to load in each transaction */
   protected int transactionSize = 0;
 
-  /**
-   * The log4j XML config file
-   */
+  /** The log4j XML config file */
   protected File logConfig = null;
 
-  /**
-   * The ITQL interpreter
-   */
+  /** The ITQL interpreter */
   protected ItqlInterpreterBean interpreter = null;
 
-  /**
-   * The load log
-   */
+  /** The load log */
   protected RDFLoadLog loadLog = null;
 
-  /**
-   * Is logging enabled
-   */
+  /** Is logging enabled */
   private boolean loggingEnabled = false;
 
-  /**
-   * Should credentials be used
-   */
+  /** Should credentials be used */
   private boolean presentCredentials = false;
 
-  /**
-   * The number of files loaded
-   */
+  /** The number of files loaded */
   private int numLoaded = 0;
 
-  /**
-   * The number of errors
-   */
+  /** The number of errors */
   private int numErrors = 0;
 
-  /**
-   * The default value for <code>autcommit</code> is on
-   */
+  /** The default value for <code>autcommit</code> is on */
   private boolean autocommit = true;
   
   /**
@@ -235,7 +190,6 @@
    * @param log The file to log to.
    */
   public void setLogfile(File log) {
-
     logFile = log;
   }
 
@@ -245,7 +199,6 @@
    * @param model The URI of the model to load into.
    */
   public void setModeluri(URI model) {
-
     modelURI = model;
   }
 
@@ -255,7 +208,6 @@
    * @param domain The security domain of server where the model resides.
    */
   public void setDomainuri(URI domain) {
-
     domainURI = domain;
   }
 
@@ -266,7 +218,6 @@
    * @param user The username to use for the security domain.
    */
   public void setUsername(String user) {
-
     username = user;
   }
 
@@ -277,7 +228,6 @@
    * @param pass The password to use for the security domain.
    */
   public void setPassword(String pass) {
-
     password = pass;
   }
 
@@ -287,7 +237,6 @@
    * @param dir The dir to load RDF from.
    */
   public void setDir(File dir) {
-
     rdfDir = dir;
   }
 
@@ -298,7 +247,6 @@
    *      loading.
    */
   public void setDropmodel(boolean drop) {
-
     dropModel = drop;
   }
 
@@ -310,7 +258,6 @@
    *      load.
    */
   public void setMaxerrors(int max) {
-
     maxErrors = max;
   }
 
@@ -320,7 +267,6 @@
    * @param ignore <code>true</code> if errors should be ignored.
    */
   public void setIgnoreErrors(boolean ignore) {
-
     ignoreErrors = ignore;
   }
 
@@ -330,7 +276,6 @@
    * @param size The number of documents loaded per transaction.
    */
   public void setTransactionsize(int size) {
-
     transactionSize = size;
   }
 
@@ -341,7 +286,6 @@
    * @param config The log4j XML config file.
    */
   public void setLogconfig(File config) {
-
     logConfig = config;
   }
 
@@ -351,7 +295,6 @@
    * @return The number of files loaded.
    */
   public int getNumLoaded() {
-
     return numLoaded;
   }
 
@@ -361,7 +304,6 @@
    * @return The number of errors that occurred.
    */
   public int getNumErrors() {
-
     return numErrors;
   }
 
@@ -371,7 +313,6 @@
    * @throws BuildException on error.
    */
   public void init() throws BuildException {
-
     super.init();
   }
 
@@ -382,9 +323,7 @@
    * @return A path element specifying the RDF location.
    */
   public Path createRdfpath() {
-
     rdfPath = new Path(this.getProject());
-
     return rdfPath;
   }
 
@@ -394,47 +333,35 @@
    * @throws BuildException on error.
    */
   public void execute() throws BuildException {
-
     try {
-
       log("Running with this config:" + eol + this.toString(), Project.MSG_DEBUG);
 
       checkParams();
-
       setupLog();
 
       if (logger.isDebugEnabled()) {
-
         logger.debug("Running with this config:" + eol + this.toString());
       }
 
       interpreter = new ItqlInterpreterBean();
 
       presentCredentials();
-
       createModel();
 
       if (dropModel) {
-
         dropModel();
         createModel();
       }
 
       loadRDF();
-    }
-    finally {
+    } finally {
 
-      if (loadLog != null) {
+      if (loadLog != null) loadLog.close();
 
-        loadLog.close();
-      }
-
       if (interpreter != null) {
-
         try {
           interpreter.close();
-        }
-        finally {
+        } finally {
           interpreter = null;
         }
       }
@@ -476,42 +403,25 @@
 
     // log4j logging
     if (logConfig != null) {
-
       try {
-
         DOMConfigurator.configure(logConfig.toURL());
-      }
-      catch (MalformedURLException me) {
-
+      } catch (MalformedURLException me) {
         throw new BuildException("Could not configure log4j!", me);
       }
-    }
-    else {
-
+    } else {
       BasicConfigurator.configure();
-
       // Disable debug
       LogManager.getLoggerRepository().setThreshold(Level.OFF);
     }
 
     if (logFile != null) {
-
       loggingEnabled = true;
 
       // Don't read from existing log as model is dropped
       try {
-
-        if (dropModel) {
-
-          loadLog = new RDFLoadLog(logFile, false);
-        }
-        else {
-
-          loadLog = new RDFLoadLog(logFile, true);
-        }
-      }
-      catch (IOException ioe) {
-
+        if (dropModel) loadLog = new RDFLoadLog(logFile, false);
+        else loadLog = new RDFLoadLog(logFile, true);
+      } catch (IOException ioe) {
         throw new BuildException("A problem occurred with the log file.", ioe);
       }
     }
@@ -527,30 +437,20 @@
    */
   protected Object getQueryResult(String query) {
 
-    if (logger.isDebugEnabled()) {
+    if (logger.isDebugEnabled()) logger.debug("Executing query: " + query);
 
-      logger.debug("Executing query: " + query);
-    }
-
     log("Executing query: " + query, Project.MSG_DEBUG);
 
-    List list = interpreter.executeQueryToList(query, true);
+    List<Object> list = interpreter.executeQueryToList(query, true);
 
     if (list.size() > 0) {
-
       Object answer = list.get(0);
-
       try {
         if (answer instanceof String) {
-
           return (String) answer;
-        }
-        else if (answer instanceof Exception) {
-
+        } else if (answer instanceof Exception) {
           return answer;
-        }
-        else {
-
+        } else {
           throw new BuildException(
               "Expected a string or exception but got a result of type: " +
               answer.getClass().getName());
@@ -564,9 +464,7 @@
           throw new BuildException("Received bad answer from query: " + query);
         }
       }
-    }
-    else {
-
+    } else {
       return null;
     }
   }
@@ -579,29 +477,22 @@
   protected void checkParams() throws BuildException {
 
     // Only some set
-    if ( (domainURI != null) && (password != null) && (username != null)) {
-
+    if ((domainURI != null) && (password != null) && (username != null)) {
       presentCredentials = true;
-    }
-    else if ( (domainURI != null) || (password != null) || (username != null)) {
-
+    } else if ( (domainURI != null) || (password != null) || (username != null)) {
       throw new BuildException("Either none or all of the attributes " +
                                "'domainuri' 'username' 'password' must be set.");
     }
 
     // Is model set?
     if (modelURI == null) {
-
       throw new BuildException("The modeluri attribute must be set.");
     }
 
     // RDF files to load
-    if ( (rdfDir != null) && (rdfPath != null)) {
-
+    if ((rdfDir != null) && (rdfPath != null)) {
       throw new BuildException("Only one of rdfpath or rdfdir may be set.");
-    }
-    else if ( (rdfDir == null) && (rdfPath == null)) {
-
+    } else if ( (rdfDir == null) && (rdfPath == null)) {
       throw new BuildException("Either one of rdfpath or rdfdir must be set.");
     }
   }
@@ -614,7 +505,6 @@
   protected void presentCredentials() throws BuildException {
 
     if (presentCredentials) {
-
       executeQuery("su <" + domainURI + "> " + username + " " + password +
                    " ;", "credentials", "Credential presented");
     }
@@ -626,7 +516,6 @@
    * @throws BuildException on error.
    */
   protected void createModel() throws BuildException {
-
     executeQuery("create <" + modelURI + "> ;", "create model",
                  "Successfully created model ");
   }
@@ -637,7 +526,6 @@
    * @throws BuildException on error.
    */
   protected void dropModel() throws BuildException {
-
     executeQuery("drop <" + modelURI + "> ;", "drop model",
                  "Successfully dropped model ");
   }
@@ -651,8 +539,7 @@
 
     // TODO: This badly needs to be refactored - but it works!! :-)
     // If no path specified, then create one using the directory specified.
-    if ( (rdfPath == null) && (rdfDir != null)) {
-
+    if ((rdfPath == null) && (rdfDir != null)) {
       createRdfpath();
 
       FileSet fileSet = new FileSet();
@@ -660,28 +547,24 @@
       rdfPath.addFileset(fileSet);
     }
 
-    Set loadSet = new HashSet();
+    Set<String> loadSet = new HashSet<String>();
     String[] fileArray = rdfPath.list();
 
     // Build set of files to load
     for (int i = 0; i < fileArray.length; i++) {
-
       if (loggingEnabled && !loadLog.isLoaded(fileArray[i])) {
-
         loadSet.add(fileArray[i]);
-      }
-      else if (!loggingEnabled) {
-
+      } else if (!loggingEnabled) {
         loadSet.add(fileArray[i]);
       }
     }
 
     // Sort the list - greater chance that problem files are grouped
     // and log will be easier to read.
-    ArrayList loadList = new ArrayList(loadSet);
+    ArrayList<String> loadList = new ArrayList<String>(loadSet);
     Collections.sort(loadList);
 
-    List transList = new ArrayList();
+    List<File> transList = new ArrayList<File>();
     int fileIndex = 0;
     numErrors = 0;
     numLoaded = 0;
@@ -694,9 +577,7 @@
       // Turn off auto commit off if it needs to be
       if (transactionSize > 0) {
       	// if on then toggle it off for transaction support
-      	if ( autocommit ) {
-          this.setAutoCommit(false);
-      	}
+      	if (autocommit) this.setAutoCommit(false);
       }
 
     	
@@ -704,16 +585,11 @@
       File file = new File(filename);
       URI fileURI = file.toURI();
 
-      Object result =
-          getQueryResult("load <" + fileURI + "> into <" + modelURI + "> ;");
+      Object result = getQueryResult("load <" + fileURI + "> into <" + modelURI + "> ;");
 
       if (result == null) {
-
-        throw new BuildException(
-            "Did not get a result back from the load file query");
-      }
-      else if (result instanceof String) {
-
+        throw new BuildException("Did not get a result back from the load file query");
+      } else if (result instanceof String) {
         String string = (String) result;
 
         if (!string.trim().startsWith("Successfully loaded ")) {
@@ -726,11 +602,8 @@
             log("Could not load file '" + filename + "'. The message was '" +
                 string + "',  continuing...", Project.MSG_INFO);
 
-            if (loggingEnabled) {
+            if (loggingEnabled) loadLog.logLoadError(file, string);
 
-              loadLog.logLoadError(file, string);
-            }
-
             // Remove file from load list
             loadList.remove(fileIndex);
 
@@ -742,40 +615,30 @@
             // since an error has occured we need to
             // set autocommit is on;
             this.setAutoCommit(true);
-          }
 
-          // Max errors reached
-          else {
+          } else {
+            // Max errors reached
 
-            log("Could not load file '" + filename + "'. The message was '" +
-                string + "'");
+            log("Could not load file '" + filename + "'. The message was '" + string + "'");
 
-            if (loggingEnabled) {
+            if (loggingEnabled) loadLog.logLoadError(file, string);
 
-              loadLog.logLoadError(file, string);
-            }
+            log("Maximum number of load errors (" + maxErrors + ") reached. Aborting load.", Project.MSG_INFO);
 
-            log("Maximum number of load errors (" + maxErrors +
-                ") reached. Aborting load.", Project.MSG_INFO);
-
             // since an error has occured we need to
             // set autocommit is on;
             this.setAutoCommit(true);            
            
             break;
           }
-        }
 
-        // Successful load
-        else {
+        } else {
+          // Successful load
 
           log("Successful load for: " + fileURI, Project.MSG_DEBUG);
 
-          if (logger.isDebugEnabled()) {
+          if (logger.isDebugEnabled()) logger.debug("Successful load for: " + fileURI);
 
-            logger.debug("Successful load for: " + fileURI);
-          }
-
           if (transactionSize > 0) {
 
             transList.add(file);
@@ -783,39 +646,30 @@
             // New transaction?
             if (transList.size() == transactionSize) {
 
-              executeQuery("commit;", "commit",
-                           "Successfully committed transaction");
+              executeQuery("commit;", "commit", "Successfully committed transaction");
 
               // Log all files in transaction
-              if (loggingEnabled) {
+              if (loggingEnabled) loadLog.logLoadedFiles(transList);
 
-                loadLog.logLoadedFiles(transList);
-              }
-
               numLoaded += transList.size();
 
               // New transaction
               transList.clear();
             }
-          }
 
-          // Not using transactions
-          else {
+          } else {
+            // Not using transactions
 
-            if (loggingEnabled) {
+            if (loggingEnabled) loadLog.logLoadedFile(file);
 
-              loadLog.logLoadedFile(file);
-            }
-
             numLoaded++;
           }
         }
 
         fileIndex++;
-      }
 
-      // Exception
-      else {
+      } else {
+        // Exception
 
         Exception ex = (Exception) result;
         StringWriter swriter = new StringWriter();
@@ -846,19 +700,15 @@
           // since an error has occured we need to
           // set autocommit is on;
           this.setAutoCommit(true);                     
-        }
 
-        // Max errors reached
-        else {
+        } else {
+          // Max errors reached
 
           log("Could not load file '" + filename + "'. The exception was " +
               eol + swriter.toString(), Project.MSG_INFO);
 
-          if (loggingEnabled) {
+          if (loggingEnabled) loadLog.logLoadError(file, swriter.toString());
 
-            loadLog.logLoadError(file, swriter.toString());
-          }
-
           log("Maximum number of load errors (" + maxErrors +
               ") reached. Aborting load.", Project.MSG_INFO);
           
@@ -881,28 +731,20 @@
         executeQuery("commit;", "commit", "Successfully committed transaction");
 
         // Log all files in transaction
-        if (loggingEnabled) {
+        if (loggingEnabled) loadLog.logLoadedFiles(transList);
 
-          loadLog.logLoadedFiles(transList);
-        }
-
         numLoaded += transList.size();
       }
 
       this.setAutoCommit(true);
     }
 
-    log("Loaded " + numLoaded + " files with " + numErrors + " errors.",
-        Project.MSG_INFO);
-    logger.info("Loaded " + numLoaded + " files with " + numErrors +
-                " errors.");
+    log("Loaded " + numLoaded + " files with " + numErrors + " errors.", Project.MSG_INFO);
+    logger.info("Loaded " + numLoaded + " files with " + numErrors + " errors.");
 
     if (loggingEnabled) {
-
-      log("Total files loaded in log is " + loadLog.getNumLoaded() + ".",
-          Project.MSG_INFO);
-      logger.info("Total files loaded in log is " + loadLog.getNumLoaded() +
-                  ".");
+      log("Total files loaded in log is " + loadLog.getNumLoaded() + ".", Project.MSG_INFO);
+      logger.info("Total files loaded in log is " + loadLog.getNumLoaded() + ".");
     }
   }
 
@@ -921,35 +763,26 @@
     Object result = getQueryResult(query);
 
     if (result == null) {
+      throw new BuildException("Did not get a result back from the " + queryName + " query");
+    } else if (result instanceof String) {
 
-      throw new BuildException("Did not get a result back from the " +
-                               queryName + " query");
-    }
-    else if (result instanceof String) {
+      String string = (String)result;
 
-      String string = (String) result;
-
       if (!string.trim().startsWith(successMessage)) {     	
         // an unexpected response. 
         throw new BuildException("Bad " + queryName + " query: " + string);
-      }
-      else {
+      } else {
 
         log("Query result: " + string, Project.MSG_DEBUG);
 
-        if (logger.isDebugEnabled()) {
-
-          logger.debug("Query result: " + string);
-        }
+        if (logger.isDebugEnabled()) logger.debug("Query result: " + string);
       }
-    }
 
-    // Exception
-    else {
+    } else {
+      // Exception
 
       Exception e = (Exception) result;
-      throw new BuildException("Bad " + queryName + " query: (" + query + ")",
-                               e);
+      throw new BuildException("Bad " + queryName + " query: (" + query + ")", e);
     }
   }
   
@@ -959,10 +792,9 @@
    * @param state value of autocommit
    */
   private void setAutoCommit( boolean state ) { 
-    if ( state ) {
+    if (state) {
       executeQuery("set autocommit on;", "autocommit on", "Auto commit is on");
-    }
-    else {
+    } else {
   	  executeQuery("set autocommit off;", "autocommit off", "Auto commit is off");      
     }
     this.autocommit = state;    

Modified: branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadLog.java
===================================================================
--- branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadLog.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadLog.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -57,39 +57,25 @@
  */
 public class RDFLoadLog {
 
-  /**
-   * Get line separator.
-   */
+  /** Get line separator. */
   private static final String eol = System.getProperty("line.separator");
 
-  /**
-   * The file to log to.
-   */
+  /** The file to log to. */
   private File logFile = null;
 
-  /**
-   * Writer for writing to the log file
-   */
+  /** Writer for writing to the log file */
   private PrintWriter logWriter = null;
 
-  /**
-   * Set of files from the log that are already loaded
-   */
-  private Set loadedFileSet = new HashSet();
+  /** Set of files from the log that are already loaded */
+  private Set<String> loadedFileSet = new HashSet<String>();
 
-  /**
-   * A buffer to log errors to
-   */
+  /** A buffer to log errors to */
   private StringBuffer errorBuffer = new StringBuffer();
 
-  /**
-   * The number of files loaded in all logged runs
-   */
+  /** The number of files loaded in all logged runs */
   private int numLoaded = 0;
 
-  /**
-   * The number of errors that occurred
-   */
+  /** The number of errors that occurred */
   private int numErrors = 0;
 
   /**
@@ -104,17 +90,13 @@
 
     logFile = file;
 
-    List loadedList = null;
+    List<String> loadedList = null;
 
-    if (read) {
+    if (read) loadedList = readLog();
 
-      loadedList = readLog();
-    }
-
     setupLogWriter();
 
-    if ( (loadedList != null) && (loadedList.size() > 0)) {
-
+    if ((loadedList != null) && (loadedList.size() > 0)) {
       writeExisting(loadedList);
     }
   }
@@ -122,22 +104,19 @@
   /**
    * Is the file already loaded.
    *
-   * @param file PARAMETER TO DO
+   * @param file The name of the file to check.
    * @return true if the file is already loaded.
    */
   public boolean isLoaded(String file) {
-
     return loadedFileSet.contains(file);
   }
 
   /**
    * Get the number of files loaded from the current and previous logged runs.
    *
-   * @return The number of files loaded from the current and previous logged
-   *      runs.
+   * @return The number of files loaded from the current and previous logged runs.
    */
   public int getNumLoaded() {
-
     return numLoaded;
   }
 
@@ -147,7 +126,6 @@
    * @return The the number of errors that occurred.
    */
   public int getNumErrors() {
-
     return numErrors;
   }
 
@@ -157,7 +135,6 @@
    * @param file The file to log as loaded.
    */
   public void logLoadedFile(File file) {
-
     logWriter.println(file.getAbsolutePath());
     logWriter.flush();
     numLoaded++;
@@ -168,13 +145,8 @@
    *
    * @param list The list of files (File objects) to log as loaded.
    */
-  public void logLoadedFiles(List list) {
-
-    Iterator iter = list.iterator();
-
-    while (iter.hasNext()) {
-
-      File file = (File) iter.next();
+  public void logLoadedFiles(List<File> list) {
+    for (File file: list) {
       logWriter.println(file.getAbsolutePath());
       numLoaded++;
     }
@@ -189,7 +161,6 @@
    * @param message An error message.
    */
   public void logLoadError(File file, String message) {
-
     errorBuffer.append("Could not load file '" + file.getAbsolutePath() +
                        "'." + eol + message + eol + eol);
     numErrors++;
@@ -201,7 +172,6 @@
    * @param message An error message.
    */
   public void logLoadError(String message) {
-
     errorBuffer.append(message + eol + eol);
     numErrors++;
   }
@@ -211,7 +181,6 @@
    *
    */
   public void close() {
-
     // Write out the errors
     logWriter.println();
     logWriter.println("Total files loaded: " + numLoaded);
@@ -238,13 +207,9 @@
    */
   private void setupLogWriter() throws IOException {
 
-    // Make the log file and any required directories
-    if (!logFile.exists()) {
-
-      logFile.getParentFile().mkdirs();
-    }
-
     if (logFile != null) {
+      // Make the log file and any required directories
+      if (!logFile.exists()) logFile.getParentFile().mkdirs();
 
       logWriter = new PrintWriter(new FileWriter(logFile));
     }
@@ -253,12 +218,12 @@
   /**
    * Reads in the files already loaded from the log file.
    *
-   * @return RETURNED VALUE TO DO
+   * @return A list of all the lines from the log file.
    * @throws IOException on error.
    */
-  private List readLog() throws IOException {
+  private List<String> readLog() throws IOException {
 
-    List loadedList = new ArrayList();
+    List<String> loadedList = new ArrayList<String>();
 
     if (logFile.exists()) {
 
@@ -266,12 +231,11 @@
       String line = inReader.readLine();
 
       // Read in the files previously loaded.
-      while ( (line != null) && (line.trim().length() != 0)) {
+      while ((line != null) && (line.trim().length() != 0)) {
 
         loadedFileSet.add(line);
 
-        // Use list as well to keep files in same log order when written out
-        // again.
+        // Use list as well to keep files in same log order when written out again.
         loadedList.add(line);
         line = inReader.readLine();
       }
@@ -287,13 +251,10 @@
    *
    * @param loadedList The list of file loaded last time.
    */
-  private void writeExisting(List loadedList) {
+  private void writeExisting(List<String> loadedList) {
 
-    Iterator iter = loadedList.iterator();
-
-    while (iter.hasNext()) {
-
-      logWriter.println(iter.next());
+    for (String file: loadedList) {
+      logWriter.println(file);
       numLoaded++;
     }
 

Modified: branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/ant-task/java/org/mulgara/ant/task/rdf/RDFLoadUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -33,7 +33,6 @@
 
 import java.io.*;
 import java.net.*;
-import java.sql.*;
 
 // Java
 import java.util.*;
@@ -44,8 +43,6 @@
 
 // Ant
 import org.apache.tools.ant.Project;
-import org.apache.tools.ant.Target;
-import org.apache.tools.ant.Task;
 import org.apache.tools.ant.types.FileSet;
 import org.apache.tools.ant.types.Path;
 import org.mulgara.itql.ItqlInterpreterBean;
@@ -74,83 +71,57 @@
  */
 public class RDFLoadUnitTest extends TestCase {
 
-  /**
-   * Log category
-   */
-  private final static Logger log =
-      Logger.getLogger(RDFLoadUnitTest.class);
+  /** Log category */
+  @SuppressWarnings("unused")
+  private final static Logger log = Logger.getLogger(RDFLoadUnitTest.class);
 
-  /**
-   * Description of the Field
-   */
+  /** URI string for rdf:type */
   String RDF_TYPE_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
 
-  /**
-   * Description of the Field
-   */
+  /** URI string for the Mulgara model/graph type */
   String MODEL_URI = "http://mulgara.org/mulgara#Model";
 
-  /**
-   * Description of the Field
-   */
+  /** URI string for journals */
   String JOURNAL_URI = "urn:medline:Journal";
 
-  /**
-   * Description of the Field
-   */
+  /** The query object */
   ItqlInterpreterBean interpreter = null;
 
-  /**
-   * Description of the Field
-   */
+  /** The name of the server */
   String hostName = null;
 
-  /**
-   * Description of the Field
-   */
+  /** The name of the graph for testing */
   String testModel = null;
 
-  /**
-   * Description of the Field
-   */
+  /** The load object */
   RDFLoad load = null;
 
-  /**
-   * Description of the Field
-   */
+  /** The directory to work under */
   String baseDir = System.getProperty("basedir");
 
-  /**
-   * Description of the Field
-   */
+  /** A directory to work with for RDF files */
   File goodRDFDir =
       new File(baseDir + File.separator + "jxdata" + File.separator +
                "ant-tasks" + File.separator + "rdf-good");
 
-  /**
-   * Description of the Field
-   */
+  /** An erroneous directory to work with for RDF files */
   File badRDFDir =
       new File(baseDir + File.separator + "jxdata" + File.separator +
                "ant-tasks" + File.separator + "rdf-bad");
 
-  /**
-   * Description of the Field
-   */
+  /** An erroneous directory to work with for RDF files */
   File badRDFDir2 =
       new File(baseDir + File.separator + "jxdata" + File.separator +
                "ant-tasks" + File.separator + "rdf-bad2");
 
-  /**
-   * Description of the Field
-   */
+  /** File to write log info into */
   File logFile = new File(TempDir.getTempDir(), "rdfload-log.txt");
 
   /**
    * Public constructor.
    *
-   * @param name PARAMETER TO DO
-   * @throws Exception EXCEPTION TO DO
+   * @param name The name of the test
+   * @throws Exception Thrown if the test cannot be set up
    */
   public RDFLoadUnitTest(String name) throws Exception {
     super(name);
@@ -162,7 +133,7 @@
    * Builds a test suite.
    *
    * @return A test suite.
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception Thrown if any of the tests cannot be set up
    */
   public static TestSuite suite() throws Exception {
 
@@ -196,14 +167,13 @@
    * Runs the tests.
    *
    * @param args The args.
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception Thrown if the tests cannot be run
    */
   public static void main(String[] args) throws Exception {
 
     String baseDir = System.getProperty("basedir");
 
     if (baseDir == null) {
-
       throw new RuntimeException("Could not get the 'basedir' system property");
     }
 
@@ -217,7 +187,6 @@
 
   /**
    * Set up for tests.
-   *
    */
   public void setUp() {
     interpreter = new ItqlInterpreterBean();
@@ -237,7 +206,6 @@
 
   /**
    * Test presenting credentials.
-   *
    */
   public void testPresentCredentials() {
 
@@ -250,12 +218,9 @@
     load.interpreter = interpreter;
 
     try {
-
       load.checkParams();
       load.presentCredentials();
-    }
-    catch (BuildException be) {
-
+    } catch (BuildException be) {
       fail("Unexpected exception whilst presenting credentials: " + be);
     }
 
@@ -263,12 +228,10 @@
     load.setUsername("");
 
     try {
-
       load.checkParams();
       load.presentCredentials();
       fail("Credential presentation should have failed");
-    }
-    catch (BuildException be) {
+    } catch (BuildException be) {
 
     }
 
@@ -276,11 +239,9 @@
     load.setDomainuri(null);
 
     try {
-
       load.checkParams();
       fail("Credential presentation should have failed");
-    }
-    catch (BuildException be) {
+    } catch (BuildException be) {
 
     }
   }
@@ -288,7 +249,7 @@
   /**
    * Test creating the model.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void testCreateDropModel() throws Exception {
 
@@ -297,23 +258,19 @@
     load.interpreter = interpreter;
 
     try {
-
       load.createModel();
-    }
-    catch (BuildException be) {
-
+    } catch (BuildException be) {
       fail("Unexpected exception whilst creating model: " + be);
     }
 
     // Check for the model
-    List list =
+    List<Object> list =
         interpreter.executeQueryToList("select 'text' from <rmi://" + hostName +
                                        "/server1#> where " + " <" + testModel +
                                        "> <" + RDF_TYPE_URI + "> <" +
                                        MODEL_URI + ">;");
 
     if (list.get(0)instanceof String) {
-
       fail("Got exception instead of answer: " + list.get(0));
     }
 
@@ -321,7 +278,6 @@
     answer.beforeFirst();
 
     if (answer.isUnconstrained() || !answer.next()) {
-
       fail("Model was not created!");
     }
     assertEquals("Query should not return multiple answers", list.size(), 1);
@@ -337,11 +293,10 @@
                                        "> <" + RDF_TYPE_URI + "> <" +
                                        MODEL_URI + ">;");
 
-    answer = (Answer) list.get(0);
+    answer = (Answer)list.get(0);
     answer.beforeFirst();
 
     if (answer.next()) {
-
       fail("Model was not dropped!");
     }
     assertEquals("Query should not return multiple answers", list.size(), 1);
@@ -351,32 +306,26 @@
     load.setModeluri(URI.create("rmi://blah"));
 
     try {
-
       load.createModel();
       fail("Model creation should have failed");
+    } catch (BuildException be) {
     }
-    catch (BuildException be) {
 
-    }
-
     // Missing model
     load.setModeluri(null);
 
     try {
-
       load.interpreter = null;
       load.execute();
       fail("Model creation should have failed");
+    } catch (BuildException be) {
     }
-    catch (BuildException be) {
-
-    }
   }
 
   /**
    * Test a normal load with no logging using a directory.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void testDirLoadNoLog() throws Exception {
 
@@ -386,13 +335,12 @@
     load.execute();
 
     Answer answer =
-        (Answer) interpreter.executeQueryToList("select $s from <" + testModel +
-                                                "> where $s <" + RDF_TYPE_URI +
-                                                "> <" + JOURNAL_URI +
+        (Answer)interpreter.executeQueryToList("select $s from <" + testModel +
+                                               "> where $s <" + RDF_TYPE_URI +
+                                               "> <" + JOURNAL_URI +
         ">;").get(0);
 
     if (answer.isUnconstrained()) {
-
       fail("The data did not load");
     }
 
@@ -407,7 +355,7 @@
   /**
    * Test a normal load with no logging using an rdf path.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void testPathLoadWithLog() throws Exception {
 
@@ -421,13 +369,12 @@
     load.execute();
 
     Answer answer =
-        (Answer) interpreter.executeQueryToList("select $s from <" + testModel +
+        (Answer)interpreter.executeQueryToList("select $s from <" + testModel +
                                                 "> where $s <" + RDF_TYPE_URI +
                                                 "> <" + JOURNAL_URI +
         ">;").get(0);
 
     if (answer.isUnconstrained()) {
-
       fail("The data did not load");
     }
 
@@ -451,7 +398,7 @@
    * This test relies on the test {@link #testPathLoadWithLog()} running first.
    * </p>
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void testReadLog() throws Exception {
 
@@ -473,7 +420,7 @@
    *
    * This test relies on the test {@link #testReadLog()} running first. </p>
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void testDropModelWithLog() throws Exception {
 
@@ -490,14 +437,12 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
@@ -509,22 +454,16 @@
       // Check loader
       assertEquals("Five documents should have been loaded!", 5,
                    load.getNumLoaded());
+    } finally {
+      // Get rid of the log file
+      if (logFile.exists()) logFile.delete();
     }
-
-    // Get rid of the log file
-    finally {
-
-      if (logFile.exists()) {
-
-        logFile.delete();
-      }
-    }
   }
 
   /**
    * The load should stop after the first error.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void test1ErrorNoLog() throws Exception {
 
@@ -533,13 +472,12 @@
     load.execute();
 
     Answer answer =
-        (Answer) interpreter.executeQueryToList("select $s from <" + testModel +
-                                                "> where $s <" + RDF_TYPE_URI +
-                                                "> <" + JOURNAL_URI +
+        (Answer)interpreter.executeQueryToList("select $s from <" + testModel +
+                                               "> where $s <" + RDF_TYPE_URI +
+                                               "> <" + JOURNAL_URI +
         ">;").get(0);
 
     if (answer.isUnconstrained()) {
-
       fail("The data did not load");
     }
 
@@ -572,14 +510,12 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
@@ -595,22 +531,16 @@
       RDFLoadLog loadLog = new RDFLoadLog(logFile, true);
       assertEquals("Wrong number of documents in log!", 1,
                    loadLog.getNumLoaded());
+    } finally {
+      // Get rid of the log file
+      if (logFile.exists()) logFile.delete();
     }
-
-    // Get rid of the log file
-    finally {
-
-      if (logFile.exists()) {
-
-        logFile.delete();
-      }
-    }
   }
 
   /**
    * The load should stop after the first 2 errors.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void test2ErrorsNoLog() throws Exception {
 
@@ -620,19 +550,17 @@
     load.execute();
 
     Answer answer =
-        (Answer) interpreter.executeQueryToList("select $s from <" + testModel +
-                                                "> where $s <" + RDF_TYPE_URI +
-                                                "> <" + JOURNAL_URI +
+        (Answer)interpreter.executeQueryToList("select $s from <" + testModel +
+                                               "> where $s <" + RDF_TYPE_URI +
+                                               "> <" + JOURNAL_URI +
         ">;").get(0);
 
     if (answer.isUnconstrained()) {
-
       fail("The data did not load");
     }
 
     // Mulgara - should be 1 loaded
-    assertEquals("Wrong number of documents loaded!", 1,
-                 answer.getRowCount());
+    assertEquals("Wrong number of documents loaded!", 1, answer.getRowCount());
     answer.close();
 
     // Should be 2 errors
@@ -642,11 +570,11 @@
   /**
    * The load should stop after the first 2 errors.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void test2ErrorsWithLog() throws Exception {
 
-    try {
+    // try {
 
       load.setModeluri(URI.create(testModel));
       load.setLogfile(logFile);
@@ -660,20 +588,17 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
       // Mulgara - should be 1 loaded
-      assertEquals("Wrong number of documents loaded!", 1,
-                   answer.getRowCount());
+      assertEquals("Wrong number of documents loaded!", 1, answer.getRowCount());
       answer.close();
 
       // Should be 2 errors
@@ -682,14 +607,9 @@
       //      // Check log
       //      RDFLoadLog loadLog = new RDFLoadLog(logFile, true);
       //      assertEquals("Wrong number of documents in log!", 1, loadLog.getNumLoaded());
-    }
-    finally {
-
-      //
-      //      if (logFile.exists()) {
-      //        logFile.delete();
-      //      }
-    }
+    // } finally {
+      //      if (logFile.exists()) logFile.delete();
+    // }
   }
 
   /**
@@ -698,7 +618,7 @@
    *
    * This test depends on {@link #test2ErrorsWithLog()}. </p>
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void test3ErrorsWithLog() throws Exception {
 
@@ -715,20 +635,17 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
       // Mulgara - should be 1 loaded as tear down would have dropped the model...
-      assertEquals("Wrong number of documents loaded!", 1,
-                   answer.getRowCount());
+      assertEquals("Wrong number of documents loaded!", 1, answer.getRowCount());
       answer.close();
 
       // Should be 3 errors
@@ -741,22 +658,16 @@
       RDFLoadLog loadLog = new RDFLoadLog(logFile, true);
       assertEquals("Wrong number of documents in log!", 2,
                    loadLog.getNumLoaded());
+    } finally {
+      // Get rid of the log file
+      if (logFile.exists()) logFile.delete();
     }
-
-    // Get rid of the log file
-    finally {
-
-      if (logFile.exists()) {
-
-        logFile.delete();
-      }
-    }
   }
 
   /**
    * Test a normal load with 1 files per transaction.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void test1PerTrans() throws Exception {
 
@@ -774,14 +685,12 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
@@ -796,20 +705,16 @@
 
       // Should be 0 errors
       assertEquals("Wrong number of errors!", 0, load.getNumErrors());
-    }
-    finally {
+    } finally {
 
-      if (logFile.exists()) {
-
-        logFile.delete();
-      }
+      if (logFile.exists()) logFile.delete();
     }
   }
 
   /**
    * Test a normal load with 5 file per transaction.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General declaration for failed tests.
    */
   public void test5PerTrans() throws Exception {
 
@@ -826,14 +731,12 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
@@ -848,14 +751,9 @@
 
       // Should be 0 errors
       assertEquals("Wrong number of errors!", 0, load.getNumErrors());
+    } finally {
+      if (logFile.exists()) logFile.delete();
     }
-    finally {
-
-      if (logFile.exists()) {
-
-        logFile.delete();
-      }
-    }
   }
 
   /**
@@ -876,7 +774,7 @@
    */
   public void test2PerTransWith1Error() throws Exception {
 
-    try {
+    // try {
 
       load.setModeluri(URI.create(testModel));
       load.setLogfile(logFile);      
@@ -890,14 +788,12 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("Null result set");
       }
 
@@ -914,13 +810,11 @@
       //      assertEquals("No documents should be logged!", 0, loadLog.getNumLoaded());
       // Should be 2 errors
       assertEquals("Wrong number of errors!", 2, load.getNumErrors());
-    }
-    finally {
-
+    // } finally {
       //      if (logFile.exists()) {
       //        logFile.delete();
       //      }
-    }
+    // }
   }
 
   /**
@@ -962,14 +856,12 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
@@ -987,14 +879,9 @@
 
       // Should be 3 errors
       assertEquals("Wrong number of errors!", 3, load.getNumErrors());
+    } finally {
+      if (logFile.exists()) logFile.delete();
     }
-    finally {
-
-      if (logFile.exists()) {
-
-        logFile.delete();
-      }
-    }
   }
 
   /**
@@ -1024,14 +911,12 @@
       load.execute();
 
       Answer answer =
-          (Answer) interpreter.executeQueryToList("select $s from <" +
-                                                  testModel +
-                                                  "> where $s <" + RDF_TYPE_URI +
-                                                  "> <" + JOURNAL_URI + ">;").
-          get(0);
+          (Answer)interpreter.executeQueryToList("select $s from <" +
+                                                 testModel +
+                                                 "> where $s <" + RDF_TYPE_URI +
+                                                 "> <" + JOURNAL_URI + ">;").get(0);
 
       if (answer.isUnconstrained()) {
-
         fail("The data did not load");
       }
 
@@ -1048,14 +933,9 @@
 
       // Should be 3 errors
       assertEquals("Wrong number of errors!", 6, load.getNumErrors());
+    } finally {
+      if (logFile.exists()) logFile.delete();
     }
-    finally {
-
-      if (logFile.exists()) {
-
-        logFile.delete();
-      }
-    }
   }
 
   /**

Modified: branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/test/ClientGraphUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/test/ClientGraphUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/test/ClientGraphUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -193,15 +193,13 @@
     log.debug("Testing Answer implementation");
 
     //get all statments from the graph
-    Answer answer = this.getEntireGraph(this.graphURI);
+    Answer answer = this.getEntireGraph(graphURI);
 
     //create a Client Graph from it.
-    ClientGraph client = AbstractGraphFactory.createGraph(answer,
-        answerBean.getSession());
+    ClientGraph client = AbstractGraphFactory.createGraph(answer, answerBean.getSession(serverURI));
 
     //ensure the client is not null
-    assertNotNull("AbstractGraphFactory.createGraph(Answer) returned a null " +
-                  "ClientGraph.", client);
+    assertNotNull("AbstractGraphFactory.createGraph(Answer) returned a null ClientGraph.", client);
 
     //close the graph
     client.close();
@@ -244,9 +242,8 @@
   public void testAnswerFind() throws Exception {
 
     //create a Client Graph from it.
-    Answer answer = this.getEntireGraph(this.graphURI);
-    ClientGraph client = AbstractGraphFactory.createGraph(answer,
-        answerBean.getSession());
+    Answer answer = this.getEntireGraph(graphURI);
+    ClientGraph client = AbstractGraphFactory.createGraph(answer, answerBean.getSession(serverURI));
     GraphElementFactory factory = client.getElementFactory();
 
     //-- FIND ALL --
@@ -533,8 +530,7 @@
   public void testAnswerOutputRDF() throws Exception {
 
     //create a Client Graph containing all statments
-    ClientGraph client1 = AbstractGraphFactory.createGraph(this.getEntireGraph(this.
-        graphURI), answerBean.getSession());
+    ClientGraph client1 = AbstractGraphFactory.createGraph(this.getEntireGraph(graphURI), answerBean.getSession(serverURI));
     File rdfOutput1 = new File(CLIENT_TEST_FILE1);
     this.outputRDF(rdfOutput1, client1);
 
@@ -544,8 +540,7 @@
     this.interpreterBean.load(rdfOutput1, graph2);
 
     //output new model
-    ClientGraph client2 = AbstractGraphFactory.createGraph(this.getEntireGraph(
-        graph2), answerBean.getSession());
+    ClientGraph client2 = AbstractGraphFactory.createGraph(this.getEntireGraph(graph2), answerBean.getSession(serverURI));
     File rdfOutput2 = new File(CLIENT_TEST_FILE2);
     this.outputRDF(rdfOutput2, client2);
 

Modified: branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java
===================================================================
--- branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -65,13 +65,11 @@
 
 //JRDF packages
 import org.jrdf.graph.*;
-import org.jrdf.util.ClosableIterator;
 
 //Mulgara packages
-import org.mulgara.itql.lexer.*;
-import org.mulgara.itql.parser.*;
-import org.mulgara.client.jrdf.*;
 import org.mulgara.itql.*;
+import org.mulgara.parser.MulgaraLexerException;
+import org.mulgara.parser.MulgaraParserException;
 import org.mulgara.query.*;
 import org.mulgara.query.rdf.*;
 import org.mulgara.server.Session;
@@ -113,7 +111,7 @@
    * @throws GraphException
    * @return Answer
    */
-  public static Answer executeQuery(String query, ItqlInterpreter interpreter,
+  public static Answer executeQuery(String query, TqlInterpreter interpreter,
                                     Session session) throws GraphException {
 
     try {
@@ -127,12 +125,12 @@
       throw new GraphException("Could not execute query: " + query,
                                queryException);
     }
-    catch (LexerException lexerException) {
+    catch (MulgaraLexerException lexerException) {
 
       throw new GraphException("Could not parse query: " + query,
                                lexerException);
     }
-    catch (ParserException parserException) {
+    catch (MulgaraParserException parserException) {
 
       throw new GraphException("Could not parse query: " + query,
                                parserException);
@@ -151,7 +149,7 @@
    * @param session Session
    * @throws GraphException
    */
-  public static void executeCommand(String command, ItqlInterpreter interpreter,
+  public static void executeCommand(String command, TqlInterpreter interpreter,
                                     Session session) throws GraphException {
 
     Answer answer = null;
@@ -232,15 +230,13 @@
    * @param modelURI String
    * @throws GraphException
    */
-  public static String getDeleteQuery(Iterator triples, String modelURI) throws
-      GraphException {
+  public static String getDeleteQuery(Iterator<Triple> triples, String modelURI) throws GraphException {
 
     //value to be returned
     StringBuffer query = new StringBuffer("");
 
     //there must be triples to insert
-    if ( (triples != null)
-        && (triples.hasNext())) {
+    if ((triples != null) && (triples.hasNext())) {
 
       query.append("delete ");
 
@@ -269,15 +265,14 @@
    * @param modelURI String
    * @throws GraphException
    */
-  public static String getInsertQuery(Iterator triples, String modelURI) throws
+  public static String getInsertQuery(Iterator<Triple> triples, String modelURI) throws
       GraphException {
 
     //value to be returned
     StringBuffer query = new StringBuffer("");
 
     //there must be triples to insert
-    if ( (triples != null)
-        && (triples.hasNext())) {
+    if ((triples != null) && (triples.hasNext())) {
 
       query.append("insert ");
 
@@ -306,8 +301,7 @@
    * @throws GraphException
    * @return String
    */
-  private static String getTripleSetQuery(Iterator triples) throws
-      GraphException {
+  private static String getTripleSetQuery(Iterator<Triple> triples) throws GraphException {
 
     //value to be returned
     StringBuffer tripleSet = new StringBuffer();
@@ -317,7 +311,7 @@
       //append each
       while (triples.hasNext()) {
 
-        tripleSet.append(getTripleString( (Triple) triples.next()));
+        tripleSet.append(getTripleString(triples.next()));
       }
     }
 

Modified: branches/mgr-73/src/jar/config/build.xml
===================================================================
--- branches/mgr-73/src/jar/config/build.xml	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/config/build.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -11,13 +11,17 @@
   <!-- =================================================================== -->
   <target name="config-generate-uptodate">
 
-    <uptodate property="config-generate-uptodate"
-       targetfile="${config.dist.dir}/${config.jar}">
-      <srcfiles dir="${conf.dir}" includes="mulgara-embedded.xsd"/>
-    </uptodate>
+    <condition property="config-generate-uptodate">
+      <and>
+        <uptodate targetfile="${config.dist.dir}/${config.jar}">
+          <srcfiles dir="${conf.dir}" includes="mulgara-embedded.xsd"/>
+        </uptodate>
+        <available file="${obj.dir}/jar/config/java" type="dir"/>
+      </and>
+    </condition>
   </target>
 
-  <target name="config-generate" depends="config-generate-uptodate"
+  <target name="config-generate"
      description="Generates the Mulgara config code" unless="config-generate-uptodate">
 
     <delete dir="${obj.dir}/jar/config/java"/>

Modified: branches/mgr-73/src/jar/connection/build.xml
===================================================================
--- branches/mgr-73/src/jar/connection/build.xml	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/build.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -19,10 +19,6 @@
   <!-- =================================================================== -->
   <path id="connection-classpath">
     <path refid="common-classpath"/>
-    <!-- FIXME: Remove iTQL JAR once the iTQL classes are moved into the iTQL package. -->
-    <fileset file="${itql.dist.dir}/${itql.jar}"/>
-    <fileset file="${query.dist.dir}/${query.jar}"/>
-    <fileset file="${rules.dist.dir}/${rules.jar}"/>
   </path>
   <path id="connection-test-classpath">
     <path refid="connection-classpath"/>
@@ -38,7 +34,7 @@
     <delete dir="${connection.dist.dir}"/>
   </target>
 
-  <target name="connection-compile" depends="-prepare-build, server-jar" description="Compiles connection classes">
+  <target name="connection-compile" depends="-prepare-build" description="Compiles connection classes">
     <mkdir dir="${connection.obj.dir}"/>
     <mkdir dir="${connection.test.dir}"/>
     <mkdir dir="${connection.dist.dir}"/>

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnection.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnection.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,94 +0,0 @@
-package org.mulgara.connection;
-
-import java.net.URI;
-
-import org.mulgara.query.Answer;
-import org.mulgara.query.Query;
-import org.mulgara.query.QueryException;
-import org.mulgara.server.Session;
-
-/**
- * Default implementation of an iTQL connection to a Mulgara store.
- *
- * @author Tom Adams
- * @version $Revision: 1.4 $
- * @created 2005-04-01
- * @modified $Date: 2005/04/04 11:30:10 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class DefaultItqlConnection implements ItqlConnection {
-
-  // FIXME: Make connections threadsafe.
-
-  private Session session;
-  private URI securityDomain;
-
-  /**
-   * Creates a new iTQL connection to a Mulgara server.
-   *
-   * @param session The session to use to communicate to the Mulgara server.
-   * @param securityDomain The security domain of the Mulgara server.
-   */
-  public DefaultItqlConnection(Session session, URI securityDomain) {
-    this.session = session;
-    this.securityDomain = securityDomain;
-  }
-
-  /**
-   * Executes a command that affects a change on the database and returns no results.
-   *
-   * @param command The command to execute.
-   * @throws InvalidQuerySyntaxException If the syntax of the query is incorrect.
-   * @throws MulgaraConnectionException If an error occurs while executing the command.
-   */
-  public void executeUpdate(String command) throws InvalidQuerySyntaxException, MulgaraConnectionException {
-    checkStringParam("command", command);
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  /**
-   * Executes a query that returns results.
-   *
-   * @param query The query to execute.
-   * @return The answer to the query, will never be <code>null</code>.
-   * @throws InvalidQuerySyntaxException If the syntax of the query is incorrect.
-   * @throws MulgaraConnectionException If an error occurs while executing the query.
-   */
-  public Answer executeQuery(String query) throws InvalidQuerySyntaxException, MulgaraConnectionException {
-    checkStringParam("query", query);
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  /**
-   * Closes the connection to the Mulgara store.
-   * <p>
-   * Calling this method will close the underlying {@link Session}, making it unusable for future use.
-   * </p>
-   *
-   * @throws MulgaraConnectionException If an error occurs while closing the connection.
-   */
-  public void close() throws MulgaraConnectionException {
-    try {
-      session.close();
-    } catch (QueryException e) {
-      throw new MulgaraConnectionException("Unable to close underlying session", e);
-    }
-  }
-
-  // FIXME: Delete this.
-  private static void checkStringParam(String name, String param) {
-    checkParamForNull(name, param);
-    checkParamForEmptyString(name, param);
-  }
-
-  // FIXME: Delete this.
-  private static void checkParamForNull(String name, Object param) {
-    if (param == null) throw new IllegalArgumentException(name+" parameter cannot be null");
-  }
-
-  // FIXME: Delete this.
-  private static void checkParamForEmptyString(String name, String param) {
-    if (param.trim().length() == 0) throw new IllegalArgumentException(name+" parameter cannot be empty");
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnectionUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnectionUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/DefaultItqlConnectionUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,55 +0,0 @@
-package org.mulgara.connection;
-
-import java.net.URI;
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
-
-import junit.framework.TestCase;
-
-import org.mulgara.connection.param.ParameterTestUtil;
-
-/**
- * Unit test for {@link DefaultItqlConnection}.
- *
- * @author Tom Adams
- * @version $Revision: 1.4 $
- * @created Apr 1, 2005
- * @modified $Date: 2005/04/04 11:30:10 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class DefaultItqlConnectionUnitTest extends TestCase {
-
-  private static final MockBadSession BAD_SESSION = new MockBadSession();
-  private static final URI NULL_SECURITY_DOMAIN = MulgaraConnectionFactory.NULL_SECURITY_DOMAIN;
-  private static final String EXECUTE_UPDATE_METHOD = "executeUpdate";
-  private static final String EXECUTE_QUERY_METHOD = "executeQuery";
-  private static final String NULL = ParameterTestUtil.NULL;
-  private static final String EMPTY_STRING = ParameterTestUtil.EMPTY_STRING;
-  private static final String SINGLE_SPACE = ParameterTestUtil.SINGLE_SPACE;
-
-  public void testClose() {
-    try {
-      new DefaultItqlConnection(BAD_SESSION, NULL_SECURITY_DOMAIN).close();
-      fail("Bad connection should throw MulgaraConnectionException");
-    } catch (MulgaraConnectionException expected) { }
-  }
-
-  public void testExecuteSimpleBadQuery() throws Exception {
-    DefaultItqlConnection connection = new DefaultItqlConnection(BAD_SESSION, NULL_SECURITY_DOMAIN);
-    checkBadParam(connection, EXECUTE_UPDATE_METHOD, NULL);
-    checkBadParam(connection, EXECUTE_UPDATE_METHOD, EMPTY_STRING);
-    checkBadParam(connection, EXECUTE_UPDATE_METHOD, SINGLE_SPACE);
-  }
-
-  public void testExecuteSimpleBadUpdate() throws Exception {
-    DefaultItqlConnection connection = new DefaultItqlConnection(BAD_SESSION, NULL_SECURITY_DOMAIN);
-    checkBadParam(connection, EXECUTE_QUERY_METHOD, NULL);
-    checkBadParam(connection, EXECUTE_QUERY_METHOD, EMPTY_STRING);
-    checkBadParam(connection, EXECUTE_QUERY_METHOD, SINGLE_SPACE);
-  }
-
-  private void checkBadParam(DefaultItqlConnection connection, String method, String param) throws Exception {
-    ParameterTestUtil.checkBadParam(connection, method, param);
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/InvalidQuerySyntaxException.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/InvalidQuerySyntaxException.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/InvalidQuerySyntaxException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,22 +0,0 @@
-package org.mulgara.connection;
-
-/**
- * Indicates that the format of a query does not match the required syntax for its language.
- *
- * @author Tom Adams
- * @version $Revision: 1.1 $
- * @created 2005-04-03
- * @modified $Date: 2005/04/03 05:02:06 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class InvalidQuerySyntaxException extends Exception {
-
-  public InvalidQuerySyntaxException(String message) {
-    super(message);
-  }
-
-  public InvalidQuerySyntaxException(String message, Throwable cause) {
-    super(message, cause);
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlConnection.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlConnection.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlConnection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,14 +0,0 @@
-package org.mulgara.connection;
-
-/**
- * A connection to a Mulgara server through which to send iTQL queries.
- *
- * @author Tom Adams
- * @version $Revision: 1.1 $
- * @created 2005-04-01
- * @modified $Date: 2005/04/03 02:26:09 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public interface ItqlConnection extends MulgaraConnection {
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilder.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilder.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilder.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,36 +0,0 @@
-package org.mulgara.connection;
-
-import java.util.HashMap;
-
-import org.mulgara.connection.param.MethodParameterUtil;
-import org.mulgara.itql.ItqlInterpreter;
-import org.mulgara.query.Query;
-
-/**
- * Builds iTQL queries in {@link String} form into {@link Query} objects.
- *
- * @author Tom Adams
- * @version $Revision: 1.1 $
- * @created 2005-04-03
- * @modified $Date: 2005/04/04 11:30:10 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlQueryBuilder implements QueryBuilder {
-
-  /**
-   * Builds an iTQL query in {@link String} form into a {@link org.mulgara.query.Query}.
-   *
-   * @param query The query in {@link String} form of the query.
-   * @return The <code>query</code> in {@link org.mulgara.query.Query} form.
-   * @throws InvalidQuerySyntaxException If the syntax of the <code>query</code> is incorrect.
-   */
-  public Query buildQuery(String query) throws InvalidQuerySyntaxException {
-    MethodParameterUtil.checkNotEmptyString("query", query);
-    try {
-      return new ItqlInterpreter(new HashMap()).parseQuery(query);
-    } catch (Exception e) {
-      throw new InvalidQuerySyntaxException("Unable to build query from string: "+query, e);
-    }
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilderUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilderUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/ItqlQueryBuilderUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,40 +0,0 @@
-package org.mulgara.connection;
-
-import junit.framework.TestCase;
-
-import org.mulgara.connection.param.ParameterTestUtil;
-
-/**
- * Unit test for {@link ItqlQueryBuilder}.
- *
- * @author Tom Adams
- * @version $Revision: 1.1 $
- * @created 2005-04-03
- * @modified $Date: 2005/04/04 11:30:10 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlQueryBuilderUnitTest extends TestCase {
-
-  private static final String BUILD_QUERY_METHOD = "buildQuery";
-  private static final String NULL = ParameterTestUtil.NULL;
-  private static final String EMPTY_STRING = ParameterTestUtil.EMPTY_STRING;
-  private static final String SINGLE_SPACE = ParameterTestUtil.SINGLE_SPACE;
-
-  public void testBadParams() throws Exception {
-    ItqlQueryBuilder builder = new ItqlQueryBuilder();
-    checkBadParam(builder, NULL);
-    checkBadParam(builder, EMPTY_STRING);
-    checkBadParam(builder, SINGLE_SPACE);
-  }
-
-  public void tesBuildQuery() throws InvalidQuerySyntaxException {
-    // FIXME: Is there any more testing we can do on the form of the query?
-    String query = "select $s $p $o from <rmi://localhost/server1#> where $s $p $o ;";
-    assertNotNull(new ItqlQueryBuilder().buildQuery(query));
-  }
-
-  private void checkBadParam(ItqlQueryBuilder builder, String param) throws Exception {
-    ParameterTestUtil.checkBadParam(builder, BUILD_QUERY_METHOD, param);
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MockBadSession.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MockBadSession.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MockBadSession.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,128 +0,0 @@
-package org.mulgara.connection;
-
-import java.net.URI;
-import java.util.Set;
-import java.util.List;
-import java.io.OutputStream;
-import java.io.InputStream;
-import javax.transaction.xa.XAResource;
-
-import org.mulgara.query.Answer;
-import org.mulgara.query.ModelExpression;
-import org.mulgara.query.Query;
-import org.mulgara.query.QueryException;
-import org.mulgara.rules.RulesRef;
-import org.mulgara.server.Session;
-
-/**
- * Mock {@link Session} for unit testing.
- *
- * @author Tom Adams
- * @version $Revision: 1.2 $
- * @created Apr 1, 2005
- * @modified $Date: 2005/06/26 12:47:55 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class MockBadSession implements Session {
-
-  public void insert(URI modelURI, Set statements) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void insert(URI modelURI, Query query) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void delete(URI modelURI, Set statements) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void delete(URI modelURI, Query query) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void backup(URI sourceURI, URI destinationURI) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void backup(URI sourceURI, OutputStream outputStream) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void restore(URI serverURI, URI sourceURI) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void restore(InputStream inputStream, URI serverURI, URI sourceURI) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public Answer query(Query query) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public List query(List queries) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void createModel(URI modelURI, URI modelTypeURI) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void removeModel(URI uri) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public boolean modelExists(URI uri) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public long setModel(URI uri, ModelExpression modelExpression) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public long setModel(InputStream inputStream, URI uri, ModelExpression modelExpression) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void setAutoCommit(boolean autoCommit) throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void commit() throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void rollback() throws QueryException {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void close() throws QueryException {
-    throw new QueryException("Implement me...");
-  }
-
-  public boolean isLocal() {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public void login(URI securityDomain, String username, char[] password) {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-  
-  public RulesRef buildRules(URI uri, URI uri2, URI uri3) {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-  
-  public void applyRules(RulesRef rulesRef) {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-  
-  public XAResource getXAResource() {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-
-  public XAResource getReadOnlyXAResource() {
-    throw new UnsupportedOperationException("Implement me...");
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnection.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnection.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,45 +0,0 @@
-package org.mulgara.connection;
-
-import org.mulgara.query.Answer;
-
-/**
- * A connection to a Mulgara store through which to send textual commands.
- * <p>
- * {@link MulgaraConnection} is the (Java) interface that query-oriented interfaces should use to connect to a Mulgara store.
- * </p>
- *
- * @created 2005-03-31
- * @author Tom Adams
- * @version $Revision: 1.3 $
- * @modified $Date: 2005/04/03 10:22:46 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public interface MulgaraConnection {
-
-  /**
-   * Executes a command that affects a change on the database and returns no results.
-   *
-   * @param command The command to execute.
-   * @throws InvalidQuerySyntaxException If the syntax of the <code>command</code> is incorrect.
-   * @throws MulgaraConnectionException If an error occurs while executing the command.
-   */
-  void executeUpdate(String command) throws InvalidQuerySyntaxException, MulgaraConnectionException;
-
-  /**
-   * Executes a query that returns results.
-   *
-   * @param query The query to execute.
-   * @return The answer to the query, will never be <code>null</code>.
-   * @throws InvalidQuerySyntaxException If the syntax of the <code>query</code> is incorrect.
-   * @throws MulgaraConnectionException If an error occurs while executing the query.
-   */
-  Answer executeQuery(String query) throws InvalidQuerySyntaxException, MulgaraConnectionException;
-
-  /**
-   * Closes the connection to the Mulgara store.
-   *
-   * @throws MulgaraConnectionException If an error occurs while closing the connection.
-   */
-  void close() throws MulgaraConnectionException;
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionException.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionException.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,22 +0,0 @@
-package org.mulgara.connection;
-
-/**
- * Indicates that a connection error occured while connected/ing to a Mulgara server.
- *
- * @author Tom Adams
- * @version $Revision: 1.2 $
- * @created 2005-03-31
- * @modified $Date: 2005/04/03 05:02:06 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class MulgaraConnectionException extends Exception {
-
-  public MulgaraConnectionException(String message) {
-    super(message);
-  }
-
-  public MulgaraConnectionException(String message, Throwable cause) {
-    super(message, cause);
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactory.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactory.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactory.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,43 +0,0 @@
-package org.mulgara.connection;
-
-import java.net.URI;
-
-import org.mulgara.query.rdf.Mulgara;
-import org.mulgara.server.Session;
-import org.mulgara.server.SessionFactory;
-
-/**
- * Returns query oriented connections to a Mulgara server.
- *
- * @author Tom Adams
- * @version $Revision: 1.2 $
- * @created Apr 1, 2005
- * @modified $Date: 2005/04/03 05:02:06 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public final class MulgaraConnectionFactory {
-
-  /**
-   * Indicates that no security is enabled for this Mulgara server.
-   */
-  // FIXME: Move this constant somewhere better so it can be used instead of null on the server also.
-  // FIXME: Replace the use of this constant in all code that currently passes null as a flag for no security.
-  public static final URI NULL_SECURITY_DOMAIN = URI.create(Mulgara.NAMESPACE+"NO_SECURITY");
-
-  /**
-   * Returns a connection to the Mulgara store through which to send iTQL queries.
-   * <p>
-   * Note. A new connection is returned for each call, they not pooled and are not thread safe. Clients should ensure
-   * that they call close on the connection once it is no longer required.
-   * </p>
-   *
-   * @param session The session to use to communicate to the Mulgara server.
-   * @param securityDomain The security domain of the Mulgara server.
-   * @return A connection to the Mulgara store through which to issue iTQL queries.
-   */
-  public ItqlConnection getItqlConnection(Session session, URI securityDomain) {
-    // FIXME: Use IoC to set this and mock it out in the unit test.
-    return new DefaultItqlConnection(session, securityDomain);
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactoryUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactoryUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/MulgaraConnectionFactoryUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,39 +0,0 @@
-package org.mulgara.connection;
-
-import java.net.URI;
-
-import junit.framework.TestCase;
-import org.mulgara.query.rdf.Mulgara;
-import org.mulgara.server.Session;
-
-/**
- * Unit test for {@link MulgaraConnectionFactory}.
- *
- * @author Tom Adams
- * @version $Revision: 1.2 $
- * @created Apr 1, 2005
- * @modified $Date: 2005/04/03 05:02:06 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class MulgaraConnectionFactoryUnitTest extends TestCase {
-
-  private static final MockBadSession BAD_SESSION = new MockBadSession();
-  private static final URI NULL_SECURITY_DOMAIN = MulgaraConnectionFactory.NULL_SECURITY_DOMAIN;
-
-  public void testNoSecurityConstant() {
-    assertEquals(URI.create("http://mulgara.org/mulgara#NO_SECURITY"), MulgaraConnectionFactory.NULL_SECURITY_DOMAIN);
-  }
-
-  public void testGetItqlConnection() {
-    MulgaraConnectionFactory factory = new MulgaraConnectionFactory();
-    assertNotNull(factory.getItqlConnection(BAD_SESSION, NULL_SECURITY_DOMAIN));
-  }
-
-  public void testBadSessionPassthrough() {
-    try {
-      new MulgaraConnectionFactory().getItqlConnection(BAD_SESSION, NULL_SECURITY_DOMAIN).close();
-      fail("Closing connection with bad session should have thrown exception");
-    } catch (MulgaraConnectionException expected) { }
-  }
-}

Deleted: branches/mgr-73/src/jar/connection/java/org/mulgara/connection/QueryBuilder.java
===================================================================
--- branches/mgr-73/src/jar/connection/java/org/mulgara/connection/QueryBuilder.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/connection/java/org/mulgara/connection/QueryBuilder.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,26 +0,0 @@
-package org.mulgara.connection;
-
-import org.mulgara.query.Query;
-
-/**
- * Builds queries in {@link String} form into {@link Query} objects.
- *
- * @author Tom Adams
- * @version $Revision: 1.1 $
- * @created 2005-04-03
- * @modified $Date: 2005/04/03 10:22:46 $
- * @copyright &copy; 2005 <a href="http://www.mulgara.org/">Mulgara Project</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public interface QueryBuilder {
-
-  /**
-   * Builds a query in {@link String} form into a {@link Query}, suitable for passing to a
-   * {@link org.mulgara.server.Session}.
-   *
-   * @param query The query in {@link String} form of the query.
-   * @return The <code>query</code> in {@link Query} form.
-   * @throws InvalidQuerySyntaxException If the syntax of the <code>query</code> is incorrect.
-   */
-  Query buildQuery(String query) throws InvalidQuerySyntaxException;
-}

Modified: branches/mgr-73/src/jar/driver/java/org/mulgara/server/driver/SessionFactoryFinder.java
===================================================================
--- branches/mgr-73/src/jar/driver/java/org/mulgara/server/driver/SessionFactoryFinder.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/driver/java/org/mulgara/server/driver/SessionFactoryFinder.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -42,6 +42,7 @@
 
 // Locally written packages
 import org.mulgara.server.*;
+import org.mulgara.util.Reflect;
 
 /**
  * Obtain a {@link SessionFactory} instance.
@@ -65,45 +66,38 @@
  */
 public abstract class SessionFactoryFinder {
 
-  /**
-   * Logger.
-   *
-   * This is named after the class.
-   */
-  private static final Logger logger =
-      Logger.getLogger(SessionFactoryFinder.class.getName());
+  /** Logger. This is named after the class. */
+  private static final Logger logger = Logger.getLogger(SessionFactoryFinder.class.getName());
 
-  /**
-   * A ZeroConf peer.
-   *
-   * This listens for servers on the LAN.
-   */
-  /*
-     private static JmDNS jmdns;
-   */
+  /* A ZeroConf peer. This listens for servers on the LAN. */
+  // private static JmDNS jmdns;
 
   /**
    * Map from a database's URI scheme to the name of a {@link SessionFactory}
    * implementation for it.
    */
-  private static final Map schemeMap = new HashMap();
+  private static final Map<String,String> schemeMap = new HashMap<String,String>();
 
+  /**
+   * Environment setup for setting up a context for the naming registry.
+   */
+  private static final Hashtable<String,String> localContextEnv = new Hashtable<String,String>();
+
   static {
     schemeMap.put("beep", "org.mulgara.server.beep.BEEPSessionFactory");
     schemeMap.put("rmi", "org.mulgara.server.rmi.RmiSessionFactory");
     schemeMap.put("local", "org.mulgara.server.local.LocalSessionFactory");
-
-    /*
-         try {
-      jmdns = new JmDNS(InetAddress.getLocalHost());
-     jmdns.addServiceListener("_itql._tcp.local", new ServerServiceListener());
-         }
-         catch (Exception e) {
-      logger.warn("Couldn't start ZeroConf peer", e);
-         }
-     */
+    localContextEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
+    localContextEnv.put(Context.PROVIDER_URL, "rmi://localhost");
+//    try {
+//      jmdns = new JmDNS(InetAddress.getLocalHost());
+//      jmdns.addServiceListener("_itql._tcp.local", new ServerServiceListener());
+//    } catch (Exception e) {
+//      logger.warn("Couldn't start ZeroConf peer", e);
+//    }
   }
 
+
   /**
    * Obtain a {@link SessionFactory} instance.  Assumes that this is being used
    * locally - within the same JVM.
@@ -133,75 +127,61 @@
       boolean isRemote) throws SessionFactoryFinderException, NonRemoteSessionException {
 
     // If no serverURI was specified, search the LAN for a local server
-    if (serverURI == null) {
-      serverURI = findServerURI();
-    }
+    if (serverURI == null) serverURI = findServerURI();
     assert serverURI != null;
 
+    String scheme = serverURI.getScheme();
+
     // Obtain the classname for the SessionFactory
     String className;
 
     // Handle RMI schemes differently.
-    if (serverURI.getScheme().equals("rmi")) {
+    if (scheme.equals("rmi")) {
       logger.debug("Attempting to connect via RMI");
       // First attempt to connect via RMI.
       try {
-        Hashtable environment = new Hashtable();
-        environment.put("java.naming.factory.initial",
-            "com.sun.jndi.rmi.registry.RegistryContextFactory");
-        environment.put("java.naming.provider.url",
-            "rmi://" + serverURI.getRawAuthority());
+        Hashtable<String,String> environment = new Hashtable<String,String>();
+        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
+        environment.put(Context.PROVIDER_URL, "rmi://" + serverURI.getRawAuthority());
         Context rmiRegistryContext = new InitialContext(environment);
-        rmiRegistryContext.lookup(serverURI.getPath()
-          .substring(1));
+        rmiRegistryContext.lookup(serverURI.getPath().substring(1));
 
         // If the lookup is successful connect using RMI.
-        className = (String) schemeMap.get(serverURI.getScheme());
+        className = (String)schemeMap.get(scheme);
       } catch (NamingException ne) {
         logger.debug("Failed to connect via RMI", ne);
 
         // If there is an exception connect locally.
         if (!isRemote) {
           logger.debug("Attempting to fallback to local", ne);
-          className = (String) schemeMap.get("local");
+          className = (String)schemeMap.get("local");
+        } else {
+          throw new SessionFactoryFinderException("Cannot find server " + serverURI, ne);
         }
-        else {
-          throw new SessionFactoryFinderException(
-              "Cannot find server " + serverURI, ne);
-        }
       }
+    } else {
+      className = (String)schemeMap.get(scheme);
     }
-    else {
-      className = (String) schemeMap.get(serverURI.getScheme());
-    }
 
     if (className == null) {
-      throw new SessionFactoryFinderException(
-          serverURI + " has unsupported scheme (" + serverURI.getScheme() + ")"
-      );
+      throw new SessionFactoryFinderException(serverURI + " has unsupported scheme (" + scheme + ")");
     }
     assert className != null;
 
     // Use reflection to create the SessionFactory
     try {
-      try {
-        return (SessionFactory) Class.forName(className).
-            getConstructor(new Class[] { URI.class }).newInstance(new Object[] {
-            serverURI});
-      } catch (java.lang.reflect.InvocationTargetException ie) {
-        // check if the exception thrown indicates we should retry
-        Throwable e = ie.getCause();
-        if (!(e instanceof NonRemoteSessionException)) {
-          throw new SessionFactoryFinderException("Couldn't create session factory for " + serverURI, e);
-        }
-        // tell the calling code
-        throw (NonRemoteSessionException)e;
+      return (SessionFactory)Reflect.newInstance(Class.forName(className), serverURI);
+    } catch (RuntimeException ie) {
+      Throwable originalEx = ie.getCause();
+      // check if the exception thrown indicates we should retry
+      Throwable e = originalEx.getCause();
+      if (!(e instanceof NonRemoteSessionException)) {
+        throw new SessionFactoryFinderException("Couldn't create session factory for " + serverURI, e);
       }
-
+      // tell the calling code
+      throw (NonRemoteSessionException)originalEx;
     } catch (Exception e) {
-      throw new SessionFactoryFinderException(
-          "Couldn't create session factory for " + serverURI, e
-      );
+      throw new SessionFactoryFinderException("Couldn't create session factory for " + serverURI, e);
     }
   }
 
@@ -209,10 +189,10 @@
    * Find a server.
    *
    * This currently only tries for a Java RMI server on the local host.
+   * Consider falling back to other hosts seen when asking for a session factory.
    *
-   * @return a Java RMI server {@link URI} for the local host, never
-   *   <code>null</code>
-   * @throws SessionFactoryFinderException  if the server URI can't be composed
+   * @return a Java RMI server {@link URI} for the local host, never <code>null</code>
+   * @throws SessionFactoryFinderException if the server URI can't be composed
    */
   public static URI findServerURI() throws SessionFactoryFinderException {
     // Look for an RMI server named "server1" on the local host
@@ -220,56 +200,34 @@
       return new URI(
           "rmi", // Java RMI protocol
           InetAddress.getLocalHost().getCanonicalHostName(), // host
-          "/server1", // default RMI server
+          "/" + getServiceName(),
           null // no fragment means this is a server, not a model
       );
+    } catch (UnknownHostException e) {
+      throw new SessionFactoryFinderException("Couldn't determine local host name", e);
+    } catch (URISyntaxException e) {
+      throw new SessionFactoryFinderException("Invalid local server URI", e);
     }
-    catch (UnknownHostException e) {
-      throw new SessionFactoryFinderException(
-          "Couldn't determine local host name", e
-      );
-    }
-    catch (URISyntaxException e) {
-      throw new SessionFactoryFinderException(
-          "Invalid local server URI", e
-      );
-    }
-
-    /*
-         throw new SessionFactoryFinderException(
-      "Null \"serverURI\" parameter - LAN search not yet implemented"
-         );
-     */
   }
 
+
   /**
-   * Method to ask the ServerInfo for the local database session.
-   * This will return null if ServerInfo is not available -
-   * ie. being run on a host which has no local database, such an an iTQL client.
-   *
-   * @throws SessionFactoryFinderException If ServerInfo can't be called.  This
-   *         should only happen on a client, which should not have asked for a local session
-   *         anyway.
+   * Lookup the local registry for any registered names.
+   * @return The first name registered with the local RMI server, or the default name if this cannot be found.
    */
-  private static SessionFactory getLocalSessionFactory() throws SessionFactoryFinderException {
-    Object factory = null;
+  private static String getServiceName() {
     try {
-      Class rsf = Class.forName("org.mulgara.server.ServerInfo");
-      java.lang.reflect.Method getLocalSessionFactory = rsf.getMethod("getLocalSessionFactory", null);
-      factory = getLocalSessionFactory.invoke(null, null);
-    } catch (Exception e) {
-      throw new SessionFactoryFinderException(
-          "Couldn't obtain a local session factory.  Unexpected problem.", e
-      );
-    }
-    if (factory == null) {
-      throw new SessionFactoryFinderException(
-          "Couldn't obtain a local session factory.  Server has no access to database."
-      );
-    }
-    return (SessionFactory)factory;
+      Context rmiRegistryContext = new InitialContext(localContextEnv);
+      // get the list of names for the default context
+      NamingEnumeration<NameClassPair> ne = rmiRegistryContext.list(rmiRegistryContext.getNameInNamespace());
+      // return the first name
+      if (ne.hasMore()) return ne.next().getName(); 
+    } catch (NamingException e) { /* fall back to the default */ }
+    
+    // error or no name found, so return the default name.
+    return SessionFactoryFactory.DEFAULT_SERVER_NAME;
   }
-
+  
   /**
    * Listens for notification via ZeroConf of servers appearing on the LAN.
    */

Modified: branches/mgr-73/src/jar/itql/build.xml
===================================================================
--- branches/mgr-73/src/jar/itql/build.xml	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/build.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -49,7 +49,7 @@
     <mkdir dir="${itql.obj.dir}/java"/>
   </target>
 
-  <target name="gen-itql-parser" depends="-prepare-build, itql-parser-uptodate, sablecc" unless="itql-parser-uptodate">
+  <target name="gen-itql-parser" depends="-itql-prepare, itql-parser-uptodate, sablecc" unless="itql-parser-uptodate">
     <sablecc src="${itql.src.dir}/sablecc" outputdirectory="${itql.obj.dir}/java">
       <include name="itql.grammar"/>
     </sablecc>
@@ -62,11 +62,11 @@
   </target>
 
   <target name="-itql-token-build-label" depends="-itql-token-build-label-uptodate" unless="itql.token.build.label.uptodate">
-    <replace file="${itql.obj.dir}/java/org/mulgara/itql/ItqlSession.java" token="@@build.label@@" value="${build.label}"/>
+    <replace file="${itql.obj.dir}/java/org/mulgara/itql/TqlSession.java" token="@@build.label@@" value="${build.label}"/>
   </target>
   <target name="-itql-token-build-label-uptodate">
-    <uptodate property="itql.token.build.label.uptodate" targetfile="${itql.obj.dir}/java/org/mulgara/itql/ItqlSession.java">
-      <srcfiles dir="${itql.src.dir}" includes="**/ItqlSession.java"/>
+    <uptodate property="itql.token.build.label.uptodate" targetfile="${itql.obj.dir}/java/org/mulgara/itql/TqlSession.java">
+      <srcfiles dir="${itql.src.dir}" includes="**/TqlSession.java"/>
     </uptodate>
   </target>
 
@@ -83,12 +83,12 @@
   <target name="-itql-create-manifest">
     <mkdir dir="${obj.dir}/META-INF"/>
     <manifest file="${obj.dir}/META-INF/MANIFEST_ITQL_BASE.MF">
-      <attribute name="Main-Class" value="org.mulgara.itql.ItqlSession"/>
+      <attribute name="Main-Class" value="org.mulgara.itql.TqlSession"/>
     </manifest>
     <manifest file="${obj.dir}/META-INF/MANIFEST_ITQL_BOOTSTRAP.MF">
       <attribute name="Main-Class" value="org.mulgara.util.Bootstrap"/>
       <attribute name="Embedded-Jar" value="${query.jar}, ${driver.jar}, ${itql.jar},${util.jar}, ${server-beep.jar}, ${server-rmi.jar}, apache-soap-2.2.jar, log4j-1.2.8.jar,jargs-0.2.jar, ${jrdf.jar}, ${saaj.jar}, ${emory-util.jar}"/>
-      <attribute name="Embedded-Main-Class" value="org.mulgara.itql.ItqlSession"/>
+      <attribute name="Embedded-Main-Class" value="org.mulgara.itql.TqlSession"/>
     </manifest>
   </target>
 
@@ -109,13 +109,12 @@
   <target name="itql-dist"
           depends="itql-uptodate, itql-jar, server-beep-jar, server-rmi-jar"
           unless="itql.uptodate"
-          description="Performs all tasks related to finalising this itql
-                       and readying it for distribution">
+          description="Performs all tasks related to finalising this itql and readying it for distribution">
 
     <mkdir dir="${obj.dir}/META-INF"/>
 
     <manifest file="${obj.dir}/META-INF/itql-MANIFEST.MF">
-      <attribute name="Main-Class" value="org.mulgara.itql.ItqlSession"/>
+      <attribute name="Main-Class" value="org.mulgara.itql.TqlSession"/>
     </manifest>
 
     <jar jarfile="${dist.dir}/${itql.jar}"
@@ -143,6 +142,7 @@
       <zipfileset src="${lib.dir}/${saaj.jar}" excludes="META-INF/**"/>
       <zipfileset src="${lib.dir}/${emory-util.jar}" excludes="META-INF/**"/>
       <zipfileset src="${lib.dir}/${jta.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/${axis.jar}" excludes="META-INF/**"/>
     </jar>
   </target>
 

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Aliasing.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/Aliasing.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Aliasing.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Aliasing.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,41 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.itql;
+
+import java.net.URI;
+import java.util.Map;
+
+/**
+ * An interface for indicating that an object holds and manages aliases.
+ * @created Sep 26, 2007
+ * @author Paul Gearon
+ * @copyright &copy;2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+interface Aliasing {
+  
+  /**
+   * Sets the alias map associated with this session.
+   *
+   * @param aliasMap the alias map associated with this interpreter
+   */
+  void setAliasMap(Map<String,URI> aliasMap);
+
+
+  /**
+   * Returns the alias map associated with this session.
+   *
+   * @return the alias namespace map associated with this session
+   */
+  Map<String,URI> getAliasMap();
+
+}

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Collaborator.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Collaborator.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/Collaborator.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -28,25 +28,17 @@
 package org.mulgara.itql;
 
 // Java APIs
-import java.io.*;
 import java.sql.*;
 import java.text.DateFormat;
 import java.util.*;
-import javax.activation.DataHandler;
 
 // Mail api
 import javax.mail.*;
 import javax.mail.internet.*;
-import javax.xml.parsers.*;
-import javax.xml.transform.*;
-import javax.xml.transform.dom.*;
-import javax.xml.transform.stream.*;
 
 // Third party packages
 import org.apache.log4j.*;
 import org.apache.soap.*;
-import org.apache.soap.rpc.*;
-import org.apache.soap.util.xml.*;
 
 // JRDF
 import org.jrdf.graph.URIReference;
@@ -58,7 +50,6 @@
 import org.mulgara.query.Variable;
 import org.mulgara.query.rdf.LiteralImpl;
 import org.mulgara.util.StringUtil;
-import org.w3c.dom.*;
 
 /**
  * Collaborator contains methods to store and manipulate annotations for the
@@ -69,12 +60,6 @@
  *
  * @author <a href="http://staff.PIsoftware.com/tate/">Tate Jones</a>
  *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:15 $
- *
- * @maintenanceAuthor $Author: newmana $
- *
  * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
  *
  * @copyright &copy; 2002-2003 <A href="http://www.PIsoftware.com/">Plugged In
@@ -84,165 +69,109 @@
  */
 public class Collaborator {
 
-  /**
-   * Get line separator.
-   */
+  /** the logging category to log to */
+  private final static Logger log = Logger.getLogger(Collaborator.class.getName());
+
+  /** Get line separator. */
   private static final String eol = System.getProperty("line.separator");
 
-  /**
-   * Default server name to query
-   */
+  /** Default server name to query */
   private static String SERVER_NAME = "server1";
 
-  /**
-   * Default server to query
-   */
+  /** Default server to query */
   private static String SERVER = "";
 
   //Determine the localhost name
   static {
-
     try {
-
       SERVER = "rmi://" + java.net.InetAddress.getLocalHost().getCanonicalHostName() +
           "/" + SERVER_NAME + "#";
     } catch (java.net.UnknownHostException ex) {
-
       System.err.print("Unable to determine local host name :" + ex.toString());
     }
   }
 
-  /**
-   * The ITQL interpreter Bean.
-   */
+  /** The ITQL interpreter Bean. */
   private static ItqlInterpreterBean itqlBean = null;
 
-  /**
-   * Default model to use
-   */
+  /** Default model to use */
   private final static String MODEL = "collaborator";
 
-  /**
-   * Namespace for document
-   */
-  private final static String NS =
-      "http://mulgara.org/mulgara/Annotation#";
+  /** Namespace for document */
+  private final static String NS = "http://mulgara.org/mulgara/Annotation#";
 
-  /**
-   * Email address predicate
-   */
+  /** Email address predicate */
   private final static String EMAIL_ADDRESS = NS + "emailAddress";
 
-  /**
-   * Nick name predicate
-   */
+  /** Nick name predicate */
   private final static String NICK_NAME = NS + "nickName";
 
-  /**
-   * Text predicate
-   */
+  /** Text predicate */
   private final static String TEXT = NS + "text";
 
-  /**
-   * documentId predicate
-   */
+  /** documentId predicate */
   private final static String DOCUMENT_ID = NS + "documentId";
 
-  /**
-   * annotationId predicate
-   */
+  /** annotationId predicate */
   private final static String ANNOTATION_ID_PREFIX = NS + "annotationId";
 
-  /**
-   * annotationId predicate
-   */
+  /** annotationId predicate */
   private final static String DATE = NS + "lastUpdate";
 
-  /**
-   * page number predicate
-   */
+  /** page number predicate */
   private final static String PAGE_NUMBER = NS + "pageNumber";
 
-  /**
-   * x position predicate
-   */
+  /** x position predicate */
   private final static String X_POSITION = NS + "xPosition";
 
-  /**
-   * y position predicate
-   */
+  /** y position predicate */
   private final static String Y_POSITION = NS + "yPosition";
 
-  /**
-   * x anchor predicate
-   */
+  /** x anchor predicate */
   private final static String X_ANCHOR = NS + "xAnchor";
 
-  /**
-   * y anchor predicate
-   */
+  /** y anchor predicate */
   private final static String Y_ANCHOR = NS + "yAnchor";
 
-  /**
-   * height predicate
-   */
+  /** height predicate */
   private final static String HEIGHT = NS + "height";
 
-  /**
-   * width predicate
-   */
+  /** width predicate */
   private final static String WIDTH = NS + "width";
 
-  /**
-   * Access key prefix
-   */
+  /** Access key prefix */
   private final static String KEY_PREFIX = NS + "key";
 
-  /**
-   * Check Mulgara for the collaborator model
-   */
+  /** Check Mulgara for the collaborator model */
   private final static String CHECK_MODEL =
       "select $model from <" + SERVER + "> " +
       "where $model <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> " +
       "<http://mulgara.org/mulgara#Model> ;";
 
-  /**
-   * Create model for collaborator
-   */
-  private final static String CREATE_MODEL = "create <" + SERVER + MODEL +
-      ">;";
+  /** Create model for collaborator */
+  private final static String CREATE_MODEL = "create <" + SERVER + MODEL + ">;";
 
-  /**
-   * Delete the collaboration model
-   */
+  /** Delete the collaboration model */
   private final static String DROP_MODEL = "drop <" + SERVER + MODEL + ">;";
 
-  /**
-   * Check for registration
-   */
+  /** Check for registration */
   private final static String CHECK_REGISTRATION =
       "select $key from <" + SERVER + MODEL + "> " + "where $key <" +
       EMAIL_ADDRESS + "> <mailto:~01> ;";
 
-  /**
-   * Check for registration
-   */
+  /** Check for registration */
   private final static String INSERT_REGISTRATION =
       "insert <" + KEY_PREFIX + "~01> <" + EMAIL_ADDRESS +
       "> <mailto:~02> into <" + SERVER + MODEL + ">; " + "insert <" +
       KEY_PREFIX +
       "~01> <" + NICK_NAME + "> '~03' into <" + SERVER + MODEL + ">; ";
 
-  /**
-   * Check for access key
-   */
+  /** Check for access key */
   private final static String CHECK_ACCESS_KEY =
       "select $emailaddress from <" + SERVER + MODEL + "> " + "where <" +
       KEY_PREFIX + "~01> $emailaddress <mailto:~02> ;";
 
-  /**
-   * Create annotation
-   */
+  /** Create annotation */
   private final static String INSERT_ANNOTATION =
       "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + EMAIL_ADDRESS +
       "> <mailto:~02> into <" + SERVER + MODEL + ">; " + "insert <" +
@@ -264,24 +193,18 @@
       ANNOTATION_ID_PREFIX + "~01> <" + DOCUMENT_ID + "> '~13' into <" + SERVER +
       MODEL + ">; ";
 
-  /**
-   * Retrieve an annotation
-   */
+  /** Retrieve an annotation */
   private final static String RETRIEVE_ANNOTATION =
       "select $predicate $object from <" + SERVER + MODEL + "> " + "where <" +
       ANNOTATION_ID_PREFIX + "~01> $predicate $object and " + "      <" +
       ANNOTATION_ID_PREFIX + "~01> <" + DOCUMENT_ID + "> '~02';";
 
-  /**
-   * Delete an annotation statement
-   */
+  /** Delete an annotation statement */
   private final static String DELETE_ANNOTATION_STATEMENT =
       "delete <" + ANNOTATION_ID_PREFIX + "~01> <~02> ~03 from <" + SERVER +
       MODEL + ">;";
 
-  /**
-   * Retrieve all annotations
-   */
+  /** Retrieve all annotations */
   private final static String RETRIEVE_ANNOTATIONS =
       "select $annotationId $emailaddress $nickname $text $pageno " +
       "$x $y $xanchor $yanchor $height $width $lastupdated $documentid " +
@@ -297,31 +220,26 @@
       "$annotationId <" + DATE + "> $lastupdated and " + "$annotationId <" +
       DOCUMENT_ID + "> $documentid ;";
 
-  /**
-   * the logging category to log to
-   */
-  private final static Logger log =
-      Logger.getLogger(Collaborator.class.getName());
+  /** Method identifier used for transaction naming */
+  private static final String EXECUTE_COMMAND_TX = "executeCommand";
 
-  /**
-   * For testing purposes only!!
-   */
+  /** Method identifier used for transaction naming */
+  private static final String ADD_ANNOTATION_TX = "addAnnotation";
+
+  /** Method identifier used for transaction naming */
+  private static final String REMOVE_ANNOTATION_TX = "removeAnnotation";
+  
+  /** For testing purposes only!! */
   public String lastAccessKeyCreated = null;
 
-  /**
-   * Date formater
-   */
+  /** Date formater */
   DateFormat dateFormat = DateFormat.getInstance();
 
-  /**
-   * Track the document updates
-   */
-  private final Map documentUpdates = new HashMap();
+  /** Track the document updates */
+  private final Map<String,Long> documentUpdates = new HashMap<String,Long>();
 
-  /**
-   * Track when a user last retrieved annotaions for a document
-   */
-  private final Map lastChecked = new HashMap();
+  /** Track when a user last retrieved annotaions for a document */
+  private final Map<String,Long> lastChecked = new HashMap<String,Long>();
 
   /**
    * The Collaborator will create the ITQL interpreter bean.
@@ -333,16 +251,11 @@
       itqlBean = new ItqlInterpreterBean();
 
       //Has the server name been determined
-      if (SERVER.length() == 0) {
+      if (SERVER.length() == 0) log.fatal("Unable to determine localhost name");
 
-        log.fatal("Unable to determine localhost name");
-      }
-
       try {
-
-        this.initializeModel();
+        initializeModel();
       } catch (Exception ex) {
-
         log.fatal("Unable to initialize collaboration model", ex);
       }
     }
@@ -355,6 +268,7 @@
   public void close() {
     if (itqlBean != null) {
       itqlBean.close();
+      itqlBean = null;
     }
   }
 
@@ -467,24 +381,19 @@
     boolean registered = false;
 
     //Check supplied parameters
-    if ( (emailAddress == null) ||
+    if ((emailAddress == null) ||
         (nickName == null) ||
         (emailAddress.length() == 0) ||
         (nickName.length() == 0)) {
 
       log.warn("Null paramaters supplied for email address or nickname");
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Email address and nick name must be supplied");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Email address and nick name must be supplied");
     }
 
     //TODO : validate email address
     //Check for existing registration
-    if (this.executeCommand(CHECK_REGISTRATION, new String[] {emailAddress}
-                            ,
-                            0, false)) {
+    if (executeCommand(CHECK_REGISTRATION, new String[] {emailAddress}, 0, false)) {
 
       //new registration required
       // TODO : create a better access key
@@ -494,28 +403,20 @@
       lastAccessKeyCreated = key;
 
       //TODO : Calculate expiry date
-      registered =
-          this.executeCommand(INSERT_REGISTRATION,
-                              new String[] {key, emailAddress, nickName}
-                              ,
+      registered = executeCommand(INSERT_REGISTRATION, new String[] {key, emailAddress, nickName},
                               "Successfully inserted", true);
 
       //Send an email with the registration key
       if (registered) {
-
-        this.sendEmail("foo at localhost", emailAddress,
+        sendEmail("foo at localhost", emailAddress,
                        "Collaborator Registration",
-                       "Welcome to Mulgara Collaborator. Your access key is " +
-                       key);
+                       "Welcome to Mulgara Collaborator. Your access key is " + key);
       }
     } else {
 
       log.warn("Existing registration already exists for " + emailAddress);
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Your Email address has already been registered");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Your Email address has already been registered");
     }
 
     return registered;
@@ -529,50 +430,36 @@
    * @param key evaulation key ?
    * @param emailAddress email address to validate against the access key
    * @return returns true is the evaluation key is valid
-   * @throws SOAPException excepted errors are : ?key is invaild, key has
-   *      expired ?
+   * @throws SOAPException excepted errors are : ?key is invaild, key has expired ?
    */
-  public boolean checkAccessKey(String key, String emailAddress) throws
-      SOAPException {
+  public boolean checkAccessKey(String key, String emailAddress) throws SOAPException {
 
     boolean accessOk = false;
 
-    //Check supplied parameters
-    if ( (emailAddress == null) ||
+    // Check supplied parameters
+    if ((emailAddress == null) ||
         (key == null) ||
         (emailAddress.length() == 0) ||
         (key.length() == 0)) {
 
       log.warn("Null paramaters supplied for email address and/or key");
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Email address and key name must be supplied");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Email address and key name must be supplied");
     }
 
     //Check for the access key
-    if (this.executeCommand(CHECK_ACCESS_KEY,
-                            new String[] {key, emailAddress}
-                            , 1, false)) {
+    if (executeCommand(CHECK_ACCESS_KEY, new String[] {key, emailAddress}, 1, false)) {
 
       if (log.isDebugEnabled()) {
-
-        log.debug("Access for key :" + key + " email address :" + emailAddress +
-                  " is ok");
+        log.debug("Access for key :" + key + " email address :" + emailAddress + " is ok");
       }
 
       accessOk = true;
     } else {
+      log.warn("Invaild access key :" + key + " for email address :" + emailAddress);
 
-      log.warn("Invaild access key :" + key + " for email address :" +
-               emailAddress);
-
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Invaild access key :" + key +
-                            " for email address :" + emailAddress);
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+                            "Invaild access key :" + key + " for email address :" + emailAddress);
     }
 
     return accessOk;
@@ -615,9 +502,8 @@
                                            String height,
                                            String width) throws SOAPException {
 
-    return this.addAnnotation(emailAddress, key, nickName, documentId, text,
-                              pageNo, xAnchor, yAnchor, x, y, height, width,
-                              true);
+    return addAnnotation(emailAddress, key, nickName, documentId, text,
+                         pageNo, xAnchor, yAnchor, x, y, height, width, true);
   }
 
   /**
@@ -632,13 +518,11 @@
    *      key is invaild, key has expired, invalid parameters supplied,
    *      annotation does not exist
    */
-  public synchronized boolean removeAnnotation(String emailAddress, String key,
-                                               String documentId,
-                                               String annotationId) throws
-      SOAPException {
+  public synchronized boolean removeAnnotation(
+      String emailAddress, String key, String documentId, String annotationId
+   ) throws SOAPException {
 
-    return this.removeAnnotation(emailAddress, key, documentId, annotationId,
-                                 true);
+    return removeAnnotation(emailAddress, key, documentId, annotationId, true);
   }
 
   /**
@@ -673,7 +557,7 @@
 
     // Check the the access key for this user.
     // Will throw an exception if the access key is incorrect
-    this.checkAccessKey(key, emailAddress);
+    checkAccessKey(key, emailAddress);
 
     //Check parameters
     if ( (documentId == null) ||
@@ -711,7 +595,7 @@
 
     // Commence a new transaction for the removing and
     // adding of a new annotation.
-    this.beginTransaction("editAnnotation");
+    beginTransaction("editAnnotation");
 
     try {
 
@@ -729,7 +613,7 @@
     } catch (SOAPException ex) {
 
       //Rollback the transaction
-      this.rollback("editAnnotation");
+      rollback("editAnnotation");
 
       // re-throw the exception
       throw ex;
@@ -739,23 +623,20 @@
     if (!added) {
 
       //Rollback the transaction
-      this.rollback("editAnnotation");
+      rollback("editAnnotation");
 
       log.warn("Unable to edit annotation documentId :" + documentId +
                " annotationId :" + annotationId);
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
                             "Unable to edit annotation");
-
-      throw se;
     } else {
 
       // Commit the changes
-      this.commit("editAnnotation");
+      commit("editAnnotation");
 
       // the flag the update document
-      this.documentHasUpdated(documentId);
+      documentHasUpdated(documentId);
     }
 
     return annotationId;
@@ -772,55 +653,42 @@
    *      is invalid, key has expired, invalid parameters supplied, invalid
    *      documentId supplied
    */
-  public synchronized String retrieveAnnotations(String emailAddress,
-                                                 String key, String documentId) throws
-      SOAPException {
+  public synchronized String retrieveAnnotations(
+      String emailAddress, String key, String documentId
+  ) throws SOAPException {
 
-    boolean retrieved = false;
-
     // Check the the access key for this user.
     // Will throw an exception if the access key is incorrect
-    this.checkAccessKey(key, emailAddress);
+    checkAccessKey(key, emailAddress);
 
     //Check parameters
     if ((documentId == null) || (documentId.length() == 0)) {
 
       log.warn("Invalid paramaters supplied for retrieving annotations");
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
           "Invalid paramaters supplied for retrieving annotations");
-      throw se;
     }
 
     String results = "";
 
     //Subsitute the parameter into the query
-    String query =
-        StringUtil.substituteStrings(RETRIEVE_ANNOTATIONS,
-                                     new String[] {documentId});
+    String query = StringUtil.substituteStrings(RETRIEVE_ANNOTATIONS, documentId);
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Executing query :" + query);
 
-      log.debug("Executing query :" + query);
-    }
-
     //Issue the query
     try {
-
-      results = this.decode(itqlBean.executeQueryToString(query));
+      results = decode(itqlBean.executeQueryToString(query));
     } catch (Exception ex) {
 
       log.error("Unable to retrieve annotations for documentId :" + documentId, ex);
 
-      SOAPException se = new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Unable to retrieve annotations: " + ex.getMessage(), ex);
-
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to retrieve annotations: " + ex.getMessage(), ex);
     }
 
     // track the document retrieval
-    this.documentHasBeenRetrieved(documentId, emailAddress);
+    documentHasBeenRetrieved(documentId, emailAddress);
 
     return results;
   }
@@ -836,32 +704,26 @@
    *      is invalid, key has expired, invalid parameters supplied, invalid
    *      documentId supplied
    */
-  public boolean checkAnnotationUpdates(String emailAddress,
-                                        String key,
-                                        String documentId)
-    throws SOAPException {
+  public boolean checkAnnotationUpdates(
+      String emailAddress, String key, String documentId
+  ) throws SOAPException {
 
     // Check the the access key for this user.
     // Will throw an exception if the access key is incorrect
-    this.checkAccessKey(key, emailAddress);
+    checkAccessKey(key, emailAddress);
 
-    //Check parameters
-    if ( (documentId == null) || (documentId.length() == 0)) {
-
+    // Check parameters
+    if ((documentId == null) || (documentId.length() == 0)) {
       log.warn("Invalid paramaters supplied for retrieving annotations");
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Invalid paramaters supplied for retrieving annotations");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for retrieving annotations");
     }
 
-    return this.hasDocumentUpdated(documentId, emailAddress);
+    return hasDocumentUpdated(documentId, emailAddress);
   }
 
   /**
-       * Checks for the collaboration model. If the model does not exist then create
-   * it.
+   * Checks for the collaboration model. If the model does not exist then create it.
    *
    * @return return true if successful with initialisation
    * @throws QueryException Unable to extract or create model
@@ -874,25 +736,20 @@
     boolean initialized = false;
 
     try {
-
-      String ans = itqlBean.executeQueryToString(CHECK_MODEL);
+      // ignore string output
+      itqlBean.executeQueryToString(CHECK_MODEL);
     } catch (Exception ex) {
 
       ex.printStackTrace();
     }
 
-    List answers = itqlBean.executeQueryToList(CHECK_MODEL);
-
-    Object obj = null;
     String model = null;
 
-    for (Iterator ai = answers.iterator(); ai.hasNext(); ) {
+    for (Object obj: itqlBean.executeQueryToList(CHECK_MODEL)) {
 
-      obj = ai.next();
-
       if (obj instanceof Answer) {
 
-        Answer answer = (Answer) obj;
+        Answer answer = (Answer)obj;
 
         try {
           //reset cursor
@@ -900,23 +757,15 @@
 
           while (answer.next()) {
 
-            model = ((URIReference) answer.getObject(answer.getColumnIndex(new
-Variable("model")))).getURI().toString();
+            model = ((URIReference)answer.getObject(answer.getColumnIndex(new Variable("model")))).getURI().toString();
 
-            if (log.isDebugEnabled()) {
+            if (log.isDebugEnabled()) log.debug("Found model :" + model);
 
-              log.debug("Found model :" + model);
-            }
-
             int pos = model.indexOf("#");
 
             if (pos >= 0) {
 
-              if (log.isDebugEnabled()) {
-
-                log.debug("Testing model :" + model.substring(pos + 1));
-              }
-
+              if (log.isDebugEnabled()) log.debug("Testing model :" + model.substring(pos + 1));
               initialized = (model.substring(pos + 1).equals(MODEL));
             }
           }
@@ -927,22 +776,18 @@
 
         if (obj instanceof String) {
 
-          log.error("Unable to check collaboration model for existance :" +
-                    ( (String) obj).toString() + " Using query :" + CHECK_MODEL);
+          log.error("Unable to check collaboration model for existance :" + obj + " Using query :" + CHECK_MODEL);
         } else {
 
-          log.error("Unable to check collaboration model for existance " +
-                    " Using query :" + CHECK_MODEL);
+          log.error("Unable to check collaboration model for existance Using query :" + CHECK_MODEL);
         }
       }
     }
 
     if (initialized == false) {
-
-      //Model has not been initialized
-      initialized = this.createModel();
+      // Model has not been initialized
+      initialized = createModel();
     } else {
-
       log.debug("Collaborator model already initialized at " + SERVER + MODEL);
     }
 
@@ -953,13 +798,12 @@
    * Creates a new collaborator model
    *
    * @return returns true if successful
-   * @throws SOAPException EXCEPTION TO DO
+   * @throws SOAPException Error creating the model on the server
    */
   public synchronized boolean createModel() throws SOAPException {
 
     log.warn("creating model " + SERVER + MODEL);
-
-    return this.executeCommand(CREATE_MODEL, "Successfully created model", false);
+    return executeCommand(CREATE_MODEL, "Successfully created model", false);
   }
 
   /**
@@ -971,8 +815,7 @@
   public synchronized boolean dropModel() throws SOAPException {
 
     log.warn("dropping model " + SERVER + MODEL);
-
-    return this.executeCommand(DROP_MODEL, "Successfully dropped model", false);
+    return executeCommand(DROP_MODEL, "Successfully dropped model", false);
   }
 
   /**
@@ -1006,27 +849,21 @@
 
     // Check the the access key for this user.
     // Will throw an exception if the access key is incorrect
-    if (trans) {
+    if (trans) checkAccessKey(key, emailAddress);
 
-      this.checkAccessKey(key, emailAddress);
-    }
-
     //Check parameters
-    if ( (documentId == null) ||
+    if ((documentId == null) ||
         (documentId.length() == 0) ||
         (annotationId == null) ||
         (annotationId.length() == 0)) {
 
       log.warn("Invalid paramaters supplied for annotation removal");
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Invalid paramaters supplied for annotation removal");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for annotation removal");
     }
 
     //Retrieve the annotation
-    Answer annotation = this.retrieveAnnotation(documentId, annotationId);
+    Answer annotation = retrieveAnnotation(documentId, annotationId);
 
     if (annotation != null) {
 
@@ -1034,11 +871,8 @@
       String object = null;
 
       //Begin a transaction to remove the statements
-      if (trans) {
+      if (trans) beginTransaction(REMOVE_ANNOTATION_TX);
 
-        this.beginTransaction("removeAnnotation");
-      }
-
       try {
 
         //Extract the predicate and object from the resultSet
@@ -1048,31 +882,22 @@
         while (annotation.next()) {
 
           //grab the predicate
-          predicate = ((URIReference) annotation.getObject(annotation.getColumnIndex(new Variable("predicate")))).getURI().toString();
+          predicate = ((URIReference)annotation.getObject(annotation.getColumnIndex(new Variable("predicate")))).getURI().toString();
 
           //grab the object - could be a literal or a resource
           int objectIndex = annotation.getColumnIndex(new Variable("object"));
           if (annotation.getObject(objectIndex) instanceof LiteralImpl) {
 
-            object =
-                "'" +
-                this.encode(((LiteralImpl) annotation.getObject(objectIndex)).getLexicalForm()) +
-                "'";
+            object = "'" + encode(((LiteralImpl) annotation.getObject(objectIndex)).getLexicalForm()) + "'";
           } else if (annotation.getObject(objectIndex) instanceof URIReference) {
 
-            object =
-                "<" +
-                ((URIReference) annotation.getObject(objectIndex)).getURI().
-                toString() +
-                ">";
+            object = "<" + ((URIReference)annotation.getObject(objectIndex)).getURI() + ">";
           }
 
-          //delete the annotation statement
-          removed =
-              this.executeCommand(DELETE_ANNOTATION_STATEMENT,
-                                  new String[] {annotationId, predicate, object}
-                                  , "Successfully",
-                                  false);
+          String[] removalParams = new String[] {annotationId, predicate, object};
+          
+          // delete the annotation statement
+          removed = executeCommand(DELETE_ANNOTATION_STATEMENT,removalParams, "Successfully", false);
 
           if (!removed) {
 
@@ -1080,48 +905,32 @@
                      documentId + " annotationId :" + annotationId +
                      " predicate :" +
                      predicate + " object :" + object);
-
-            SOAPException se =
-                new SOAPException(Constants.FAULT_CODE_SERVER,
-                                  "Unable to remove annotation");
-            throw se;
+            throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to remove annotation");
           } else {
 
             // the flag the update document
-            this.documentHasUpdated(documentId);
+            documentHasUpdated(documentId);
           }
         }
 
         // Commit the deletions
-        if (trans) {
+        if (trans) commit(REMOVE_ANNOTATION_TX);
 
-          this.commit("removeAnnotation");
-        }
       } catch (TuplesException ex) {
+        // Rollback the transaction
+        if (trans) rollback(REMOVE_ANNOTATION_TX);
 
-        //Rollback the transaction
-        if (trans) {
-
-          this.rollback("removeAnnotation");
-        }
-
         log.error("Unable to locate annotation for removal documentId :" +
                   documentId + " annotationId :" + annotationId, ex);
 
-        SOAPException se =
-            new SOAPException(Constants.FAULT_CODE_SERVER,
-                              "Unable to locate annotation for removal");
-        throw se;
+        throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to locate annotation for removal");
       }
     } else {
 
       log.warn("Unable to locate annotation for removal documentId :" +
                documentId + " annotationId :" + annotationId);
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Unable to locate annotation for removal");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to locate annotation for removal");
     }
 
     return removed;
@@ -1159,21 +968,18 @@
                                String pageNo,
                                String xAnchor, String yAnchor, String x,
                                String y, String height,
-                               String width, boolean trans) throws
-      SOAPException {
+                               String width, boolean trans
+  ) throws SOAPException {
 
     String annotationId = "";
 
     // Check the the access key for this user.
     // Will throw an exception if the access key is incorrect
     // Only check if not nested in another transaction
-    if (trans) {
+    if (trans) checkAccessKey(key, emailAddress);
 
-      this.checkAccessKey(key, emailAddress);
-    }
-
-    //Check parameters
-    if ( (documentId == null) ||
+    // Check parameters
+    if ((documentId == null) ||
         (documentId.length() == 0) ||
         (pageNo == null) ||
         (pageNo.length() == 0) ||
@@ -1192,73 +998,51 @@
 
       log.warn("Invalid paramaters supplied for annotation");
 
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Invalid paramaters supplied for annotation");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for annotation");
     }
 
-    //Correct the text if null
-    if (text == null) {
+    // Correct the text if null
+    if (text == null) text = "";
 
-      text = "";
-    }
-
     // Create the supporting attributes
     Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
     String lastUpdated = dateFormat.format(cal.getTime());
 
-    //TODO : create a better annotation id
+    // TODO : create a better annotation id
     annotationId = String.valueOf(System.currentTimeMillis());
 
     if (log.isDebugEnabled()) {
-
       log.debug("Adding annotation with documentId :" + documentId +
                 " email address :" + emailAddress + " nickName :" + nickName +
-                " text :" + text + " pageNo :" + pageNo + " xAnchor :" +
-                xAnchor +
-                " yAnchor :" + yAnchor + " x :" + x + " y:" + y + " height :" +
-                height +
-                " width :" + width + " lastUpdated :" + lastUpdated +
-                " annotationId :" + annotationId);
+                " text :" + text + " pageNo :" + pageNo + " xAnchor :" + xAnchor +
+                " yAnchor :" + yAnchor + " x :" + x + " y:" + y +
+                " height :" + height + " width :" + width +
+                " lastUpdated :" + lastUpdated + " annotationId :" + annotationId);
     }
 
     // Start a transaction for all the inserts
-    if (trans) {
+    if (trans) beginTransaction(ADD_ANNOTATION_TX);
 
-      this.beginTransaction("addAnnotation");
-    }
+    String[] annotationParams = new String[] {
+        annotationId, emailAddress, nickName, encode(text), pageNo,
+        xAnchor, yAnchor, x, y, height, width, lastUpdated, documentId
+    };
 
-    boolean added =
-        this.executeCommand(INSERT_ANNOTATION,
-                            new String[] {
-                            annotationId, emailAddress, nickName,
-                            this.encode(text), pageNo,
-                            xAnchor, yAnchor, x, y, height, width, lastUpdated,
-                            documentId
-    }
-        , "Successfully inserted", false);
+    // Clear the annotationId if unsuccessful - handling transactions at this level
+    if (!executeCommand(INSERT_ANNOTATION, annotationParams, "Successfully inserted", false)) {
 
-    // Clear the annotationId if unsuccessful
-    if (!added) {
-
       annotationId = "";
 
       // Rollback the inserts
-      if (trans) {
+      if (trans) rollback(ADD_ANNOTATION_TX);
 
-        this.rollback("addAnnotation");
-      }
     } else {
 
       // Commit the inserts
-      if (trans) {
+      if (trans) commit(ADD_ANNOTATION_TX);
 
-        this.commit("addAnnotation");
-      }
-
       // the flag the update document
-      this.documentHasUpdated(documentId);
+      documentHasUpdated(documentId);
     }
 
     return annotationId;
@@ -1290,108 +1074,77 @@
    * @return returns true if the expect result is found in the response
    * @throws SOAPException EXCEPTION TO DO
    */
-  private boolean executeCommand(String command, String[] substituteArray,
-                                 String expectedResult, boolean trans) throws
-      SOAPException {
+  private boolean executeCommand(
+      String command, String[] substituteArray, String expectedResult, boolean trans
+  ) throws SOAPException {
 
     boolean successful = false;
 
     //Perform any subsitutions
     if (substituteArray != null) {
-
       command = StringUtil.substituteStrings(command, substituteArray);
     }
 
-    Object obj = null;
     String message = null;
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Executing command :" + command);
 
-      log.debug("Executing command :" + command);
-    }
-
     // Commence a new transaction if required
-    if (trans) {
+    if (trans) beginTransaction(EXECUTE_COMMAND_TX);
 
-      this.beginTransaction("executeCommand");
-    }
+    // Issue the itql command
+    for (Object obj: itqlBean.executeQueryToList(command)) {
 
-    //Issue the itql command
-    List answers = itqlBean.executeQueryToList(command);
-
-    for (Iterator ai = answers.iterator(); ai.hasNext(); ) {
-
-      //Check the result
-      obj = ai.next();
-
-      //Is the result a message?
+      // Is the result a message?
       if (obj instanceof String) {
 
-        message = (String) obj;
+        message = (String)obj;
 
-        if (log.isDebugEnabled()) {
+        if (log.isDebugEnabled()) log.debug("returned message :" + message);
 
-          log.debug("returned message :" + message);
-        }
-
         // Check the outcome against the expect result
-        successful = ( (message != null) &&
-                      (message.indexOf(expectedResult) >= 0));
+        successful = ((message != null) && (message.indexOf(expectedResult) >= 0));
 
         // break if failure occurs
         if (!successful) {
-
+          log.error("Collaborator command: " + command + "\nmessage: " + message + "\nexpected: " + expectedResult);
           break;
         }
       }
 
-      //Is the result an ansert?
+      // Is the result an answer?
       if (obj instanceof Answer) {
 
         try {
 
-          //Check the number of rows returned
-          long solutionCount = ( (Answer) obj).getRowUpperBound();
+          // Check the number of rows returned
+          long solutionCount = ((Answer)obj).getRowUpperBound();
 
-          if (log.isDebugEnabled()) {
+          if (log.isDebugEnabled()) log.debug("found answer :" + solutionCount);
 
-            log.debug("found answer :" + solutionCount);
-          }
-
           message = String.valueOf(solutionCount);
 
           // Check the outcome against the expect result
-          successful = ( (message != null) &&
-                        (message.indexOf(expectedResult) >= 0));
+          successful = ((message != null) && (message.indexOf(expectedResult) >= 0));
 
           // break if failure occurs
-          if (!successful) {
+          if (!successful) break;
 
-            break;
-          }
         } catch (TuplesException ex) {
 
           log.error("Error executing command :" + command, ex);
-
-          //Rollback the changes
-          if (trans) {
-
-            this.rollback("executeCommand");
-          }
+          // Rollback the changes
+          if (trans) rollback(EXECUTE_COMMAND_TX);
+          return false;
         }
       }
     }
 
-    // Commit the changes
-    if (trans) {
+    // Commit the changes whether successful or not
+    if (trans) commit(EXECUTE_COMMAND_TX);
 
-      this.commit("executeCommand");
-    }
-
     if (log.isDebugEnabled()) {
-
-      log.debug("Command :" + command + "message :" + message + " result :" +
-                successful);
+      log.debug("Command :" + command + "message :" + message + " result :" + successful);
     }
 
     return successful;
@@ -1426,7 +1179,6 @@
         StringUtil.substituteStrings(RETRIEVE_ANNOTATION,
                                      new String[] {annotationId, documentId});
 
-    Object obj = null;
     Answer answer = null;
 
     if (log.isDebugEnabled()) {
@@ -1435,14 +1187,8 @@
     }
 
     //Issue the query command
-    List answers = itqlBean.executeQueryToList(query);
+    for (Object obj: itqlBean.executeQueryToList(query)) {
 
-    //Iterate over the results ( only return the first resultSet )
-    for (Iterator ai = answers.iterator(); ai.hasNext(); ) {
-
-      //Check the result
-      obj = ai.next();
-
       //Check for an answer
       if (obj instanceof Answer) {
 
@@ -1520,20 +1266,19 @@
     //Find out when the user performed the last retrieval for a document
     if (lastChecked.containsKey(documentId + emailAddress)) {
 
-      lastCheckedTime =
-          ( (Long) lastChecked.get(documentId + emailAddress)).longValue();
+      lastCheckedTime = lastChecked.get(documentId + emailAddress).longValue();
     }
 
     //Find out the last updated time
     if (documentUpdates.containsKey(documentId)) {
 
       // has been updated
-      lastUpdatedTime = ( (Long) documentUpdates.get(documentId)).longValue();
+      lastUpdatedTime = documentUpdates.get(documentId).longValue();
     } else {
 
       // No modification has occur for this document.
       // ie. server has been started without any updates
-      this.documentHasUpdated(documentId);
+      documentHasUpdated(documentId);
     }
 
     //Is the last check time less than the last updated time?
@@ -1553,98 +1298,66 @@
   /**
    * Commence a new transaction for this session
    *
-   * @param name PARAMETER TO DO
-   * @throws SOAPException EXCEPTION TO DO
+   * @param name Name of this transaction
+   * @throws SOAPException Unable to create a transaction on the server
    */
   private void beginTransaction(String name) throws SOAPException {
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Begin transaction : " + name);
 
-      log.debug("Begin transaction : " + name);
-    }
-
     try {
-
       itqlBean.beginTransaction(name);
     } catch (QueryException ex) {
-
-      log.error("Unable to obtain a transaction for the Mulgara Collaborator <" +
-                name + ">", ex);
-
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Unable to obtain a transaction for the Mulgara Collaborator <" +
-          name + ">");
-      throw se;
+      log.error("Unable to obtain a transaction for the Mulgara Collaborator <" + name + ">", ex);
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+          "Unable to obtain a transaction for the Mulgara Collaborator <" + name + ">");
     }
   }
 
   /**
    * Commit the current transaction
    *
-   * @param name PARAMETER TO DO
-   * @throws SOAPException EXCEPTION TO DO
+   * @param name Name of the transaction to commit
+   * @throws SOAPException Unable to commit the transaction on the server
    */
   private void commit(String name) throws SOAPException {
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Commit transaction : " + name);
 
-      log.debug("Commit transaction : " + name);
-    }
-
     try {
-
       itqlBean.commit(name);
     } catch (QueryException ex) {
-
-      log.error("Unable to obtain a transaction for the Mulgara Collaborator <" +
-                name + ">", ex);
-
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Unable to commit changes for the Mulgara Collaborator <" + name +
-          ">");
-
-      throw se;
+      log.error("Unable to obtain a transaction for the Mulgara Collaborator <" + name + ">", ex);
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+          "Unable to commit changes for the Mulgara Collaborator <" + name + ">");
     }
   }
 
   /**
    * Rollback the current transaction
    *
-   * @param name PARAMETER TO DO
-   * @throws SOAPException EXCEPTION TO DO
+   * @param name Name of the transaction to roll back
+   * @throws SOAPException Unable to roll back the transaction
    */
   private void rollback(String name) throws SOAPException {
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Rollback transaction : " + name);
 
-      log.debug("Rollback transaction : " + name);
-    }
-
     try {
-
       itqlBean.rollback(name);
     } catch (QueryException ex) {
+      log.error("Unable to rollback a transaction for the Mulgara Collaborator <" + name + ">", ex);
 
-      log.error(
-          "Unable to rollback a transaction for the Mulgara Collaborator <" +
-          name + ">",
-          ex);
-
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Unable to rollback a transaction for the Mulgara Collaborator <" +
-          name + ">");
-      throw se;
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+          "Unable to rollback a transaction for the Mulgara Collaborator <" + name + ">");
     }
   }
 
   /**
    * Encode a literal string
    *
-   * @param value PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
+   * @param value String to encode
+   * @return A new encoded string 
    */
   private String encode(String value) {
 
@@ -1654,8 +1367,8 @@
   /**
    * Decode a literal string
    *
-   * @param value PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
+   * @param value The string to decode
+   * @return A new decoded string
    */
   private String decode(String value) {
 

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CollaboratorUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CollaboratorUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CollaboratorUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -60,11 +60,9 @@
  */
 public class CollaboratorUnitTest extends TestCase {
 
-  /**
-   * Logger.
-   */
-  private final static Category logger =
-      Category.getInstance(CollaboratorUnitTest.class.getName());
+  /** Logger. */
+  @SuppressWarnings("unused")
+  private final static Category logger = Category.getInstance(CollaboratorUnitTest.class.getName());
 
   /**
    * a flag to indicate if the collorator requires closing
@@ -73,9 +71,7 @@
    */
   private boolean closeCollaborator = false;
 
-  /**
-   * Collaborator to be tested;
-   */
+  /** Collaborator to be tested; */
   Collaborator collaborator = null;
 
   /**
@@ -135,7 +131,7 @@
    * @throws IOException Description of Exception
    */
   public void tearDown() throws IOException {
-    if ( closeCollaborator ) {
+    if (closeCollaborator) {
       collaborator.close();
     }
   }
@@ -147,8 +143,7 @@
    */
   public void initializeModelTest() throws Exception {
 
-    this.assertTrue("Failed to initialize collaborator model",
-        collaborator.initializeModel());
+    assertTrue("Failed to initialize collaborator model", collaborator.initializeModel());
   }
 
   /**
@@ -159,18 +154,14 @@
 
     try {
 
-      this.assertTrue("Failed to drop collaborator model",
-          collaborator.dropModel());
+      assertTrue("Failed to drop collaborator model", collaborator.dropModel());
 
-      this.assertTrue("Expected collaborator model to be droped",
-          collaborator.dropModel() == false);
+      assertTrue("Expected collaborator model to be droped", collaborator.dropModel() == false);
 
-      this.assertTrue("Failed to create collaborator model",
-          collaborator.createModel());
+      assertTrue("Failed to create collaborator model", collaborator.createModel());
     } catch (SOAPException ex) {
-
       ex.printStackTrace();
-      this.assertTrue("Model tests failed " + ex.getMessage(), false);
+      fail("Model tests failed " + ex.getMessage());
     }
   }
 
@@ -181,32 +172,25 @@
 
     try {
 
-      this.assertTrue("Register user",
-          collaborator.register("xyz at company.com", "Joe Brown"));
+      assertTrue("Register user", collaborator.register("xyz at company.com", "Joe Brown"));
     } catch (SOAPException ex) {
-
       ex.printStackTrace();
-      this.assertTrue("Registration test failed " + ex.getMessage(), false);
+      fail("Registration test failed " + ex.getMessage());
     }
 
     try {
-
       collaborator.register("xyz at company.com", "Alex Mole");
-      this.assertTrue("Failed to detect duplicate registered user", false);
+      fail("Failed to detect duplicate registered user");
     } catch (SOAPException ex) {
-
-      this.assertTrue("Failed to get the expected message (Your Email address has already been registered)",
-          ex.getMessage().equals(
-          "Your Email address has already been registered"));
+      assertTrue("Failed to get the expected message (Your Email address has already been registered)",
+          ex.getMessage().equals("Your Email address has already been registered"));
     }
 
     try {
-
       collaborator.register("", "Alex Mole");
-      this.assertTrue("Failed to detect empty email address", false);
+      fail("Failed to detect empty email address");
     } catch (SOAPException ex) {
-
-      this.assertTrue("Failed to get the expected message (Email address and nick name must be supplied)",
+      assertTrue("Failed to get the expected message (Email address and nick name must be supplied)",
           ex.getMessage().equals("Email address and nick name must be supplied"));
     }
   }
@@ -218,28 +202,23 @@
 
     try {
 
-      this.assertTrue("Unable to register user",
-          collaborator.register("guest at pisoftware.com", "Guest User"));
+      assertTrue("Unable to register user", collaborator.register("guest at mulgara.org", "Guest User"));
 
-      this.assertTrue("Expected to find registered user with key :" +
+      assertTrue("Expected to find registered user with key :" +
           collaborator.lastAccessKeyCreated +
-          " email address : guest at pisoftware.com",
+          " email address : guest at mulgara.org",
           collaborator.checkAccessKey(collaborator.lastAccessKeyCreated,
-          "guest at pisoftware.com"));
+          "guest at mulgara.org"));
     } catch (SOAPException ex) {
-
       ex.printStackTrace();
-      this.assertTrue("Not expecting exception on checking access key " +
-          ex.getMessage(), false);
+      fail("Not expecting exception on checking access key " + ex.getMessage());
     }
 
     try {
-
-      collaborator.checkAccessKey("12345", "guest at pisoftware.com");
-      this.assertTrue("Failed to detect invalid access key", false);
+      collaborator.checkAccessKey("12345", "guest at mulgara.org");
+      fail("Failed to detect invalid access key");
     } catch (SOAPException ex) {
-
-      this.assertTrue("Failed to get the expected message (Invaild access key)",
+      assertTrue("Failed to get the expected message (Invaild access key)",
           ex.getMessage().indexOf("Invaild access key") >= 0);
     }
   }
@@ -251,54 +230,43 @@
 
     //Add a successful annotation
     try {
+      assertTrue("Unable to register user", collaborator.register("guest2 at mulgara.org", "Guest User 2"));
 
-      this.assertTrue("Unable to register user",
-          collaborator.register("guest2 at pisoftware.com", "Guest User 2"));
-
       String annotationId =
-          collaborator.addAnnotation("guest2 at pisoftware.com",
+          collaborator.addAnnotation("guest2 at mulgara.org",
           collaborator.lastAccessKeyCreated, "Guest User 2", "1234567890",
           "This is a test annotation", "1", "10", "11", "100", "101", "50",
           "50");
 
-      this.assertTrue("Unable to add annotation",
-          (annotationId != null) && (annotationId.length() > 0));
+      assertTrue("Unable to add annotation", (annotationId != null) && (annotationId.length() > 0));
     } catch (SOAPException ex) {
-
       ex.printStackTrace();
-      this.assertTrue("Failed to add annotation", false);
+      fail("Failed to add annotation");
     }
 
     // Add an invalid annotation - incorrect key
     try {
-
-      String annotationId =
-          collaborator.addAnnotation("guest2 at pisoftware.com", "badkey",
+      collaborator.addAnnotation("guest2 at mulgara.org", "badkey",
           "Guest User 2", "1234567890", "This is a test annotation", "1", "10",
           "11", "100", "101", "50", "50");
 
-      this.assertTrue("Expected bad access key error", false);
+      fail("Expected bad access key error");
     } catch (SOAPException ex) {
-
-      this.assertTrue("Failed to get the expected message (Invaild access key)",
+      assertTrue("Failed to get the expected message (Invaild access key)",
           ex.getMessage().indexOf("Invaild access key") >= 0);
     }
 
     // Add an invalid annotation - empty parameters
     try {
-
-      String annotationId =
-          collaborator.addAnnotation("guest2 at pisoftware.com",
+      collaborator.addAnnotation("guest2 at mulgara.org",
           collaborator.lastAccessKeyCreated, "Guest User 2", "1234567890",
           "This is a another annotation test", "", "", "11", "100", "101",
           "50", "50");
 
-      this.assertTrue("Expected bad parameters supplied", false);
+      fail("Expected bad parameters supplied");
     } catch (SOAPException ex) {
-
-      this.assertTrue("Failed to get the expected message (Invalid paramaters supplied for annotation)",
-          ex.getMessage().indexOf("Invalid paramaters supplied for annotation") >=
-          0);
+      assertTrue("Failed to get the expected message (Invalid paramaters supplied for annotation)",
+          ex.getMessage().indexOf("Invalid paramaters supplied for annotation") >= 0);
     }
   }
 
@@ -311,42 +279,34 @@
 
     //Add and remove an annotation
     try {
+      assertTrue("Unable to register user", collaborator.register("guest3 at mulgara.org", "Guest User 3"));
 
-      this.assertTrue("Unable to register user",
-          collaborator.register("guest3 at pisoftware.com", "Guest User 3"));
-
       annotationId =
-          collaborator.addAnnotation("guest3 at pisoftware.com",
+          collaborator.addAnnotation("guest3 at mulgara.org",
           collaborator.lastAccessKeyCreated, "Guest User 3", "1234567890",
           "This is a test annotation", "1", "10", "11", "100", "101", "50",
           "50");
 
-      this.assertTrue("Unable to add annotation",
-          (annotationId != null) && (annotationId.length() > 0));
+      assertTrue("Unable to add annotation", (annotationId != null) && (annotationId.length() > 0));
 
-      this.assertTrue("Unable to remove annotation",
-          collaborator.removeAnnotation("guest3 at pisoftware.com",
+      assertTrue("Unable to remove annotation",
+          collaborator.removeAnnotation("guest3 at mulgara.org",
           collaborator.lastAccessKeyCreated, "1234567890", annotationId));
     } catch (SOAPException ex) {
-
       ex.printStackTrace();
-      this.assertTrue("Failed to add/remove annotation", false);
+      fail("Failed to add/remove annotation");
     }
 
     // Test removing an annotation that does not exist
     try {
-
-      this.assertTrue("Unable to remove annotation",
-          collaborator.removeAnnotation("guest3 at pisoftware.com",
+      assertTrue("Unable to remove annotation",
+          collaborator.removeAnnotation("guest3 at mulgara.org",
           collaborator.lastAccessKeyCreated, "1234567890", annotationId));
-
-      this.assertTrue("Expected not to be a successful removal", false);
+      fail("Expected not to be a successful removal");
     } catch (SOAPException ex) {
-
-      this.assertTrue(
+      assertTrue(
           "Failed to get the expected message (Unable to locate annotation for removal)",
-          ex.getMessage().indexOf("Unable to locate annotation for removal") >=
-          0);
+          ex.getMessage().indexOf("Unable to locate annotation for removal") >= 0);
     }
   }
 
@@ -359,30 +319,26 @@
 
     //Add and remove an annotation
     try {
+      assertTrue("Unable to register user", collaborator.register("guest4 at mulgara.org", "Guest User 4"));
 
-      this.assertTrue("Unable to register user",
-          collaborator.register("guest4 at pisoftware.com", "Guest User 4"));
-
       annotationId =
-          collaborator.addAnnotation("guest4 at pisoftware.com",
+          collaborator.addAnnotation("guest4 at mulgara.org",
           collaborator.lastAccessKeyCreated, "Guest User 4", "1234567890",
           "This is a test annotation with a single ' quote", "1", "10", "11",
           "100", "101", "50", "50");
 
-      this.assertTrue("Unable to add annotation for editing test",
-          (annotationId != null) && (annotationId.length() > 0));
+      assertTrue("Unable to add annotation for editing test", (annotationId != null) && (annotationId.length() > 0));
 
       annotationId =
-          collaborator.editAnnotation("guest4 at pisoftware.com",
+          collaborator.editAnnotation("guest4 at mulgara.org",
           collaborator.lastAccessKeyCreated, "Guest User 4", "1234567890",
           annotationId, "This is an edited annotation with a single ' quote",
           "10", "100", "110", "1000", "1010", "500", "500");
 
-      this.assertTrue("Unable to edit annotation", annotationId != null);
+      assertTrue("Unable to edit annotation", annotationId != null);
     } catch (SOAPException ex) {
-
       ex.printStackTrace();
-      this.assertTrue("Failed to add/edit annotation", false);
+      fail("Failed to add/edit annotation");
     }
   }
 
@@ -396,47 +352,45 @@
     //Add and remove an annotation
     try {
 
-      this.assertTrue("Unable to register user",
-          collaborator.register("guest5 at pisoftware.com", "Guest User 5"));
+      assertTrue("Unable to register user",
+          collaborator.register("guest5 at mulgara.org", "Guest User 5"));
 
-      this.assertTrue("Expect document to be updated for retrieval",
-          collaborator.checkAnnotationUpdates("guest5 at pisoftware.com",
+      assertTrue("Expect document to be updated for retrieval",
+          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
           collaborator.lastAccessKeyCreated, "newdocumentId"));
 
       annotationId =
-          collaborator.addAnnotation("guest5 at pisoftware.com",
+          collaborator.addAnnotation("guest5 at mulgara.org",
           collaborator.lastAccessKeyCreated, "Guest User 5", "newdocumentId",
           "Annotation text one", "1", "10", "11", "100", "101", "50", "50");
 
       annotationId =
-          collaborator.addAnnotation("guest5 at pisoftware.com",
+          collaborator.addAnnotation("guest5 at mulgara.org",
           collaborator.lastAccessKeyCreated, "Guest User 5", "newdocumentId",
           "Annotation text two", "2", "20", "22", "200", "202", "52", "52");
 
-      this.assertTrue("Unable to add annotation for retreving test",
+      assertTrue("Unable to add annotation for retreving test",
           (annotationId != null) && (annotationId.length() > 0));
 
-      this.assertTrue("Expect document to be updated for retrieval",
-          collaborator.checkAnnotationUpdates("guest5 at pisoftware.com",
+      assertTrue("Expect document to be updated for retrieval",
+          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
           collaborator.lastAccessKeyCreated, "newdocumentId"));
 
       String results =
-          collaborator.retrieveAnnotations("guest5 at pisoftware.com",
+          collaborator.retrieveAnnotations("guest5 at mulgara.org",
           collaborator.lastAccessKeyCreated, "newdocumentId");
 
-      this.assertTrue("Unable to retrieve annotation",
+      assertTrue("Unable to retrieve annotation",
           (results != null) && (results.length() > 0) &&
           (results.indexOf("newdocumentId") >= 0));
 
-      this.assertTrue("Expect document not to be updated for retrieval",
-          collaborator.checkAnnotationUpdates("guest5 at pisoftware.com",
+      assertTrue("Expect document not to be updated for retrieval",
+          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
           collaborator.lastAccessKeyCreated, "newdocumentId") == false);
     } catch (SOAPException ex) {
-
       ex.printStackTrace();
-      this.assertTrue("Failed to add/retrieve annotation", false);
+      fail("Failed to add/retrieve annotation");
     } finally {
-
       // force the teardown to close the collaborator
       closeCollaborator = true;
     }

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CommandSplitter.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/CommandSplitter.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CommandSplitter.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CommandSplitter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,31 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.itql;
+
+import java.util.List;
+
+/**
+ * This interface splits queries for the appropriate query type
+ * @created Sep 11, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+interface CommandSplitter {
+  
+  /**
+   * Split the given string into an array of strings containing individual elements.
+   * @param All the commands in a long string.
+   * @return An array of individual commands.
+   */
+  List<String> split(String commands);
+}

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredListBuilder.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredListBuilder.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredListBuilder.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -60,12 +60,6 @@
  *
  * @author Andrae Muys
  *
- * @version $Revision: 1.1.1.1 $
- *
- * @modified $Date: $ by $Author: $
- *
- * @maintenanceAuthor $Author: $
- *
  * @company <a href="mailto:mail at netymon.com">Netymon Pty Ltd</a>
  *
  * @copyright &copy;2006 Australian Commonwealth Government.
@@ -77,15 +71,16 @@
 
   private final static Logger logger = Logger.getLogger(CompoundPredListBuilder.class.getName());
 
-  private List predLists;
+  private List<CompoundPredicate> predLists;
+
   /**
    * Constructor.
    */
   public CompoundPredListBuilder() {
-    predLists = new ArrayList();
+    predLists = new ArrayList<CompoundPredicate>();
   }
 
-  public List getPredLists() {
+  public List<CompoundPredicate> getPredLists() {
     return predLists;
   }
 
@@ -97,24 +92,18 @@
   }
 
   public void caseAColonExistsExpression(AColonExistsExpression expr) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found a colon exists expression: " + expr);
-    }
+    if (logger.isDebugEnabled()) logger.debug("Found a colon exists expression: " + expr);
     expr.getExistsExpression().apply(this);
     expr.getExistsPterm().apply(this);
   }
 
   public void caseAEtermExistsExpression(AEtermExistsExpression expr) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found a colon exists expression: " + expr);
-    }
+    if (logger.isDebugEnabled()) logger.debug("Found a colon exists expression: " + expr);
     expr.getExistsPterm().apply(this);
   }
 
   public void caseAPtermExistsPterm(APtermExistsPterm rawTerm) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found an Existential Predicate Term: " + rawTerm);
-    }
+    if (logger.isDebugEnabled()) logger.debug("Found an Existential Predicate Term: " + rawTerm);
 
     ObjectListBuilder builder = new ObjectListBuilder();
     rawTerm.getExistsOterm().apply(builder);
@@ -123,9 +112,7 @@
   }
 
   public void defaultCase(Node node) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found node in pred builder: " + node + "::" + node.getClass());
-    }
+    if (logger.isDebugEnabled()) logger.debug("Found node in pred builder: " + node + "::" + node.getClass());
   }
 }
 

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredicate.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredicate.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/CompoundPredicate.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -43,14 +43,12 @@
 package org.mulgara.itql;
 
 // Java 2 standard packages
-import java.util.ArrayList;
 import java.util.List;
 
 // Third party packages
-import org.apache.log4j.Logger; 
+// import org.apache.log4j.Logger; 
 
 // Generated packages
-import org.mulgara.itql.analysis.*;
 import org.mulgara.itql.node.*;
 
 /**
@@ -61,12 +59,6 @@
  *
  * @author Andrae Muys
  *
- * @version $Revision: 1.1.1.1 $
- *
- * @modified $Date: 2005/10/30 19:21:08 $ by $Author: prototypo $
- *
- * @maintenanceAuthor $Author: prototypo $
- *
  * @company <a href="mailto:mail at netymon.com">Netymon Pty Ltd</a>
  *
  * @copyright &copy;2006 Australian Commonwealth Government.
@@ -76,25 +68,21 @@
  */
 public class CompoundPredicate {
 
-  private final static Logger logger = Logger.getLogger(CompoundPredicate.class.getName());
+  // private final static Logger logger = Logger.getLogger(CompoundPredicate.class.getName());
 
   private PElement predicate;
-  private List objList;
+  private List<PElement> objList;
 
   /** Constructor */
-  public CompoundPredicate(PElement predicate, List objList) {
-    if (predicate == null) {
-      throw new IllegalArgumentException("predicate may not be null");
-    }
-    if (objList == null) {
-      throw new IllegalArgumentException("object list may not be null");
-    }
+  public CompoundPredicate(PElement predicate, List<PElement> objList) {
+    if (predicate == null) throw new IllegalArgumentException("predicate may not be null");
+    if (objList == null) throw new IllegalArgumentException("object list may not be null");
 
     this.predicate = predicate;
     this.objList = objList;
   }
 
-  public List getObjectList() {
+  public List<PElement> getObjectList() {
     return objList;
   }
 

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ConstraintExpressionBuilder.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ConstraintExpressionBuilder.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ConstraintExpressionBuilder.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -38,7 +38,6 @@
 // Java 2 standard packages
 import java.net.*;
 import java.util.ArrayList;
-import java.util.Iterator;
 import java.util.List;
 
 // Third party packages
@@ -61,12 +60,6 @@
  *
  * @author Andrew Newman
  *
- * @version $Revision: 1.9 $
- *
- * @modified $Date: 2005/04/10 00:00:06 $ by $Author: pgearon $
- *
- * @maintenanceAuthor $Author: pgearon $
- *
  * @company <a href="mailto:info at PIsoftware.com">Plugged In Software</a>
  *
  * @copyright &copy;2004 <a href="http://www.pisoftware.com/">Plugged In
@@ -76,31 +69,20 @@
  */
 public class ConstraintExpressionBuilder extends AnalysisAdapter {
 
-  /**
-   * The logger
-   */
-  private final static Logger logger =
-      Logger.getLogger(ConstraintExpressionBuilder.class.getName());
+  /** The logger */
+  private final static Logger logger = Logger.getLogger(ConstraintExpressionBuilder.class.getName());
 
-  /**
-   * The internal result of parsing a constraint expression.
-   */
+  /** The internal result of parsing a constraint expression. */
   private ConstraintExpression constraintExpression = null;
 
-  /**
-   * URI Syntax Exception - not null if exception occurred since last get.
-   */
+  /** URI Syntax Exception - not null if exception occurred since last get. */
   private URISyntaxException uriException = null;
 
-  /**
-   * Query Exception - not null if exception occurred since last get.
-   */
+  /** Query Exception - not null if exception occurred since last get. */
   private QueryException queryException = null;
 
-  /**
-   * The iTQL interpreter
-   */
-  private ItqlInterpreter interpreter;
+  /** The iTQL interpreter */
+  private SableCCInterpreter interpreter;
 
   /**
    * Create a new builder.  Requires methods on the interpreter in order to
@@ -108,7 +90,7 @@
    *
    * @param newInterpreter the interpreter to use.
    */
-  public ConstraintExpressionBuilder(ItqlInterpreter newInterpreter) {
+  public ConstraintExpressionBuilder(SableCCInterpreter newInterpreter) {
     interpreter = newInterpreter;
   }
 
@@ -121,68 +103,53 @@
    * @throws URISyntaxException if the constraint contains a resource whose
    *     text violates <a href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
    */
-  public ConstraintExpression getConstraintExpression() throws QueryException,
-      URISyntaxException {
+  public ConstraintExpression getConstraintExpression() throws QueryException, URISyntaxException {
     try {
       ConstraintExpression tmpExpression = constraintExpression;
 
       if (uriException != null) {
         throw uriException;
-      }
-      else if (queryException != null) {
+      } else if (queryException != null) {
         throw queryException;
-      }
-      else {
+      } else {
         return tmpExpression;
       }
-    }
-    finally {
+    } finally {
       uriException = null;
       queryException = null;
       constraintExpression = null;
     }
   }
 
+
   /**
    * Sets constraint expression.  Will set URIException or QueryException if
    * an exception occurs.
    *
    * @param newConstraintExpression the new expression.
    */
-  private void setConstraintExpression(ConstraintExpression
-      newConstraintExpression) {
+  private void setConstraintExpression(ConstraintExpression newConstraintExpression) {
     constraintExpression = newConstraintExpression;
   }
 
-  public void caseAConstraintConstraintFactor(
-      AConstraintConstraintFactor rawConstraintFactor) {
 
-    // log that we've got a constraint constraint factor
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found constraint constraint factor " + rawConstraintFactor);
-    }
+  public void caseAConstraintConstraintFactor(AConstraintConstraintFactor rawConstraintFactor) {
 
+    if (logger.isDebugEnabled()) logger.debug("Found constraint constraint factor " + rawConstraintFactor);
+
     // get the constraint
-    PConstraint constraint =
-        ((AConstraintConstraintFactor) rawConstraintFactor).getConstraint();
+    PConstraint constraint = ((AConstraintConstraintFactor)rawConstraintFactor).getConstraint();
 
-    // log that we've found a constraint
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found constraint " + constraint + ", resolving components");
-    }
+    if (logger.isDebugEnabled()) logger.debug("Found constraint " + constraint + ", resolving components");
 
     // get the constraint's components
     try {
       Constraint tmpConstraint;
 
-      ConstraintElement subject =
-          toConstraintElement(((AConstraint) constraint).getSubject());
-      ConstraintElement predicate =
-          toConstraintElement(((AConstraint) constraint).getPredicate());
-      ConstraintElement object =
-          toConstraintElement(((AConstraint) constraint).getObject());
+      ConstraintElement subject = toConstraintElement(((AConstraint)constraint).getSubject());
+      ConstraintElement predicate = toConstraintElement(((AConstraint)constraint).getPredicate());
+      ConstraintElement object = toConstraintElement(((AConstraint)constraint).getObject());
 
-      // log the components we've found
       if (logger.isDebugEnabled()) {
         logger.debug("Found subject " + subject);
         logger.debug("Found predicate " + predicate);
@@ -190,20 +157,15 @@
       }
 
       // check for an IN clause
-      AInClause inClause = (AInClause) ((AConstraint) constraint).getInClause();
+      AInClause inClause = (AInClause)((AConstraint)constraint).getInClause();
 
       // bundle them into a constraint (order is probably important here...?)
       if (inClause != null) {
-        if (logger.isDebugEnabled()) {
-          logger.debug("Found model " + inClause.getElement());
-        }
+        if (logger.isDebugEnabled()) logger.debug("Found model " + inClause.getElement());
 
-        ConstraintElement model =
-            toConstraintElement(inClause.getElement());
-        tmpConstraint =
-            ConstraintFactory.newConstraint(subject, predicate, object, model);
-      }
-      else {
+        ConstraintElement model = toConstraintElement(inClause.getElement());
+        tmpConstraint = ConstraintFactory.newConstraint(subject, predicate, object, model);
+      } else {
         tmpConstraint = ConstraintFactory.newConstraint(subject, predicate, object);
       }
 
@@ -213,95 +175,72 @@
       }
 
       // Set new value.
-      if (logger.isDebugEnabled()) {
-        logger.debug("Setting constraint: " + tmpConstraint);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Setting constraint: " + tmpConstraint);
 
       setConstraintExpression(tmpConstraint);
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
+
   /**
    * Handle a constraint expression.  Will set URIException or QueryException if
    * an exception occurs.
    *
-   * @param rawConstraintFactor the expression to create a constraint expression
-   *   from.
+   * @param rawConstraintFactor the expression to create a constraint expression from.
    */
-  public void caseAExpressionConstraintFactor(
-      AExpressionConstraintFactor rawConstraintFactor) {
+  public void caseAExpressionConstraintFactor(AExpressionConstraintFactor rawConstraintFactor) {
 
     try {
       ConstraintExpression tmpConstraintExpression;
 
-      // log that we've got an expression constraint factor
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found factor expression constraint factor " +
-            rawConstraintFactor);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Found factor expression constraint factor " + rawConstraintFactor);
 
       // get the constraint expression
       PConstraintExpression embeddedConstraintExpression =
-          ((AExpressionConstraintFactor) rawConstraintFactor).
-          getConstraintExpression();
+          ((AExpressionConstraintFactor)rawConstraintFactor).getConstraintExpression();
 
-      // log that we're recursing with a constraint expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with constraint factor " +
-            embeddedConstraintExpression);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint factor " + embeddedConstraintExpression);
 
       // build the constraint expression
-      ConstraintExpressionBuilder builder =
-          new ConstraintExpressionBuilder(interpreter);
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
       embeddedConstraintExpression.apply((Switch) builder);
 
       tmpConstraintExpression = builder.getConstraintExpression();
 
       // handle negated expressions
       if (((AExpressionConstraintFactor) rawConstraintFactor).getExclude() != null) {
-        tmpConstraintExpression = new ConstraintNegation(
-            (Constraint) tmpConstraintExpression);
+        tmpConstraintExpression = new ConstraintNegation((Constraint)tmpConstraintExpression);
       }
 
       setConstraintExpression(tmpConstraintExpression);
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
+
   /**
    * Handle a transitive constraint.  Will set URIException or QueryException if
    * an exception occurs.
    *
    * @param rawConstraintFactor a transitive constraint.
    */
-  public void caseATransitiveConstraintFactor(
-      ATransitiveConstraintFactor rawConstraintFactor) {
+  public void caseATransitiveConstraintFactor(ATransitiveConstraintFactor rawConstraintFactor) {
 
     try {
       ConstraintExpression tmpConstraintExpression = null;
 
-      // log that we've found a transitive predicate expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found factor of transitive expression" +
-            rawConstraintFactor);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Found factor of transitive expression" + rawConstraintFactor);
 
       // get the constraint transitive
       PTransitiveClause embeddedTransitiveConstraint =
-          ((ATransitiveConstraintFactor) rawConstraintFactor).
-          getTransitiveClause();
+          ((ATransitiveConstraintFactor) rawConstraintFactor).getTransitiveClause();
 
       if (embeddedTransitiveConstraint instanceof ATransitive1TransitiveClause) {
 
@@ -309,39 +248,32 @@
         tmpConstraintExpression = new SingleTransitiveConstraint(
             buildConstraint(((ATransitive1TransitiveClause)
             embeddedTransitiveConstraint).getConstraint()));
-      }
-      else if (embeddedTransitiveConstraint instanceof ATransitive2TransitiveClause) {
+      } else if (embeddedTransitiveConstraint instanceof ATransitive2TransitiveClause) {
 
         // build the transitive constraint expression
-        ATransitive2TransitiveClause tmpClause = (ATransitive2TransitiveClause)
-            embeddedTransitiveConstraint;
+        ATransitive2TransitiveClause tmpClause = (ATransitive2TransitiveClause)embeddedTransitiveConstraint;
         Constraint constraint1 = buildConstraint(tmpClause.getConstraint1());
         Constraint constraint2 = buildConstraint(tmpClause.getConstraint2());
-        tmpConstraintExpression = new TransitiveConstraint(constraint1,
-            constraint2);
+        tmpConstraintExpression = new TransitiveConstraint(constraint1, constraint2);
       }
 
       setConstraintExpression(tmpConstraintExpression);
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
-   /*
+
+  /**
     * Handle a existential compound constraint.
     */
-   public void caseAExistentialConstraintFactor(
-       AExistentialConstraintFactor rawFactor) {
-    if (logger.isDebugEnabled()) {
-       logger.debug("Found existential - constraint factor " + rawFactor);
-     }
+   public void caseAExistentialConstraintFactor(AExistentialConstraintFactor rawFactor) {
+     if (logger.isDebugEnabled()) logger.debug("Found existential - constraint factor " + rawFactor);
      try {
        setConstraintExpression(
-         buildExistential(
+           buildExistential(
            interpreter.nextAnonVariable(),
            rawFactor.getExistsExpression(),
            (AInClause)rawFactor.getInClause()));
@@ -352,17 +284,15 @@
      }
    }
 
-   /*
+
+   /**
     * Handle a concrete compound constraint.
     */
-   public void caseACompoundConstraintFactor(
-       ACompoundConstraintFactor rawFactor) {
-     if (logger.isDebugEnabled()) {
-       logger.debug("Found compound - constraint factor " + rawFactor);
-     }
+   public void caseACompoundConstraintFactor(ACompoundConstraintFactor rawFactor) {
+     if (logger.isDebugEnabled()) logger.debug("Found compound - constraint factor " + rawFactor);
      try {
        setConstraintExpression(
-         buildExistential(
+           buildExistential(
            toConstraintElement(rawFactor.getSubject()),
            rawFactor.getExistsExpression(),
            (AInClause)rawFactor.getInClause()));
@@ -374,35 +304,25 @@
    }
            
    public ConstraintExpression buildExistential(ConstraintElement subject, PExistsExpression rawTerm, AInClause in)
-       throws URISyntaxException, QueryException
-   {
-     if (logger.isDebugEnabled()) {
-       logger.debug("building existential subject: " + subject + " term.class: " + rawTerm.getClass());
-     }
+       throws URISyntaxException, QueryException {
+
+     if (logger.isDebugEnabled()) logger.debug("building existential subject: " + subject + " term.class: " + rawTerm.getClass());
  
      CompoundPredListBuilder builder = new CompoundPredListBuilder();
      rawTerm.apply(builder);
  
-     if (logger.isDebugEnabled()) {
-       logger.debug("CompoundPredListBuilder built: " + builder.getPredLists());
-     }
+     if (logger.isDebugEnabled()) logger.debug("CompoundPredListBuilder built: " + builder.getPredLists());
  
-     ConstraintElement model = in == null ? null : toConstraintElement(in.getElement());
+     ConstraintElement model = (in == null) ? null : toConstraintElement(in.getElement());
  
      // forall predicates in list forall objects in pred's obj-list
      //    add new constraint(s,p,o) to argList.
-     List argList = new ArrayList();
+     List<ConstraintExpression> argList = new ArrayList<ConstraintExpression>();
  
-     Iterator p = builder.getPredLists().iterator();
-     while (p.hasNext()) {
-       CompoundPredicate plist = (CompoundPredicate)p.next();
- 
+     for (CompoundPredicate plist: builder.getPredLists()) {
        ConstraintElement predicate = toConstraintElement(plist.getPredicate());
  
-       Iterator o = plist.getObjectList().iterator();
-       while (o.hasNext()) {
-         PElement oelem = (PElement)o.next();
- 
+       for (PElement oelem: plist.getObjectList()) {
          ConstraintElement object = toConstraintElement(oelem);
  
          if (model == null) {
@@ -413,85 +333,68 @@
        }
      }
  
-     if (logger.isDebugEnabled()) {
-       logger.debug("Existential term = and(" + argList + ")");
-     }
+     if (logger.isDebugEnabled()) logger.debug("Existential term = and(" + argList + ")");
  
      return new ConstraintConjunction(argList);
    }
-                
-  /**
+
+
+   /**
    * Handle a walk constraint.
    *
    * @param rawConstraintFactor a walk constraint.
    */
-  public void caseAWalkConstraintFactor(AWalkConstraintFactor
-      rawConstraintFactor) {
+  public void caseAWalkConstraintFactor(AWalkConstraintFactor rawConstraintFactor) {
 
     try {
-
       // Build the walk constraint
-      AWalk1WalkClause embeddedWalkConstraint = (AWalk1WalkClause)
-          ((AWalkConstraintFactor) rawConstraintFactor).getWalkClause();
+      AWalk1WalkClause embeddedWalkConstraint =
+          (AWalk1WalkClause)((AWalkConstraintFactor)rawConstraintFactor).getWalkClause();
 
       ConstraintExpression tmpConstraintExpression = new WalkConstraint(
           buildConstraint(embeddedWalkConstraint.getConstraint1()),
           buildConstraint(embeddedWalkConstraint.getConstraint2()));
 
       setConstraintExpression(tmpConstraintExpression);
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
+
   /**
    * Handle an OR constraint.  Will set URIException or QueryException if
    * an exception occurs.
    *
    * @param rawConstraintExpression an OR constraint.
    */
-  public void caseAOrConstraintExpression(
-      AOrConstraintExpression rawConstraintExpression) {
+  public void caseAOrConstraintExpression(AOrConstraintExpression rawConstraintExpression) {
 
     try {
+      if (logger.isDebugEnabled()) logger.debug("Found OR constraint expression " +rawConstraintExpression);
 
-      // log that we've found a OR constraint expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found OR constraint expression " +
-            rawConstraintExpression);
-      }
-
       // get the OR constraint expression
       PConstraintExpression orConstraintExpression =
-          ((AOrConstraintExpression) rawConstraintExpression).
-          getConstraintExpression();
+          ((AOrConstraintExpression)rawConstraintExpression).getConstraintExpression();
 
       // get the constraint term
       PConstraintTerm constraintTerm =
-          ((AOrConstraintExpression) rawConstraintExpression).getConstraintTerm();
+          ((AOrConstraintExpression)rawConstraintExpression).getConstraintTerm();
 
-      // log that we've found the operands of the disjunction
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with constraint expression " +
-            orConstraintExpression + " & constraint term " +
-            constraintTerm);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint expression " +
+            orConstraintExpression + " & constraint term " + constraintTerm);
 
       // Construct a builder to process the constraints.
-      ConstraintExpressionBuilder builder =
-          new ConstraintExpressionBuilder(interpreter);
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
 
       // get the LHS and RHS operands of the disjunction
-      orConstraintExpression.apply((Switch) builder);
+      orConstraintExpression.apply((Switch)builder);
       ConstraintExpression lhs = builder.getConstraintExpression();
-      constraintTerm.apply((Switch) builder);
+      constraintTerm.apply((Switch)builder);
       ConstraintExpression rhs = builder.getConstraintExpression();
 
-      // log that we've resolved the operands
       if (logger.isDebugEnabled()) {
         logger.debug("Resolved LHS disjunction operand " + lhs);
         logger.debug("Resolved RHS disjunction operand " + rhs);
@@ -499,11 +402,9 @@
 
       // apply the disjunction
       setConstraintExpression(new ConstraintDisjunction(lhs, rhs));
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
@@ -514,86 +415,66 @@
    *
    * @param rawConstraintExpression a term constraint.
    */
-  public void caseATermConstraintExpression(
-      ATermConstraintExpression rawConstraintExpression) {
+  public void caseATermConstraintExpression(ATermConstraintExpression rawConstraintExpression) {
 
     try {
+      if (logger.isDebugEnabled()) logger.debug("Found term constraint expression " + rawConstraintExpression);
 
-      // log that we've got a term constraint expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found term constraint expression " +
-            rawConstraintExpression);
-      }
-
       // get the constraint term
       PConstraintTerm constraintTerm =
-          ((ATermConstraintExpression) rawConstraintExpression).
-          getConstraintTerm();
+          ((ATermConstraintExpression) rawConstraintExpression).getConstraintTerm();
 
-      // log that we're about to resolve the term into an expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with constraint term " + constraintTerm);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint term " + constraintTerm);
 
       // Create a new builder.
-      ConstraintExpressionBuilder builder =
-          new ConstraintExpressionBuilder(interpreter);
-      constraintTerm.apply((Switch) builder);
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
+      constraintTerm.apply((Switch)builder);
 
       // drill down into the constraint term
       setConstraintExpression(builder.getConstraintExpression());
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
+
   /**
    * Handle a dterm constraint term.  Will set URIException or QueryException
    * if an exception occurs.
    *
    * @param rawConstraintTerm a dterm constraint term.
    */
-  public void caseADtermConstraintTerm(
-      ADtermConstraintTerm rawConstraintTerm) {
+  public void caseADtermConstraintTerm(ADtermConstraintTerm rawConstraintTerm) {
 
     try {
+      if (logger.isDebugEnabled()) logger.debug("Found dterm contraint term " + rawConstraintTerm);
 
-      // log that we've got a dterm constraint term
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found dterm contraint term " + rawConstraintTerm);
-      }
-
       // get the constraint factor
       PConstraintDterm constraintDterm =
-          ((ADtermConstraintTerm) rawConstraintTerm).getConstraintDterm();
+          ((ADtermConstraintTerm)rawConstraintTerm).getConstraintDterm();
 
       ConstraintExpression tmpConstraintExpression = null;
 
       // drill down into the constraint factor
-      ConstraintExpressionBuilder builder =
-          new ConstraintExpressionBuilder(interpreter);
-      constraintDterm.apply((Switch) builder);
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
+      constraintDterm.apply((Switch)builder);
       tmpConstraintExpression = builder.getConstraintExpression();
       setConstraintExpression(tmpConstraintExpression);
 
-      // log that we're recursing with a constraint factor
       if (logger.isDebugEnabled()) {
         logger.debug("Recursing with constraint factor " + constraintDterm);
         logger.debug("Got: " + tmpConstraintExpression);
       }
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
+
   /**
    * Handle a AND constraint term.  Will set URIException or QueryException if
    * an exception occurs.
@@ -604,10 +485,7 @@
 
     try {
 
-      // log that we've got a AND constraint term
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found AND contraint term " + rawConstraintTerm);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Found AND contraint term " + rawConstraintTerm);
 
       // get the constraint term
       PConstraintTerm constraintTerm =
@@ -617,24 +495,19 @@
       PConstraintDterm constraintDterm =
           ((AAndConstraintTerm) rawConstraintTerm).getConstraintDterm();
 
-      // log that we've found the operands of the disjunction
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with constraint term " + constraintTerm +
+      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint term " + constraintTerm +
             " & constraint factor " + constraintDterm);
-      }
 
-      ConstraintExpressionBuilder builder =
-          new ConstraintExpressionBuilder(interpreter);
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
 
       // get the LHS and RHS operands of the conjunction
-      constraintTerm.apply((Switch) builder);
+      constraintTerm.apply((Switch)builder);
       ConstraintExpression lhs = builder.getConstraintExpression();
 
       // Create another constraint builder and assign to RHS.
       constraintDterm.apply((Switch) builder);
       ConstraintExpression rhs = builder.getConstraintExpression();
 
-      // log that we've resolved the operands
       if (logger.isDebugEnabled()) {
         logger.debug("Resolved LHS conjunction operand " + lhs);
         logger.debug("Resolved RHS conjunction operand " + rhs);
@@ -642,27 +515,24 @@
 
       // apply the conjunction
       setConstraintExpression(new ConstraintConjunction(lhs, rhs));
-    }
-    catch (URISyntaxException use) {
+
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
+
   /**
    * Handle a factor constraint dterm.  Will set URIException or QueryException
    * if an exception occurs.
    *
    * @param rawConstraintTerm a factor constraint dterm.
    */
-  public void caseAFactorConstraintDterm(
-      AFactorConstraintDterm rawConstraintTerm) {
+  public void caseAFactorConstraintDterm(AFactorConstraintDterm rawConstraintTerm) {
 
     try {
-
-      // log that we've got a factor constraint term
       logger.debug("Found factor contraint term " + rawConstraintTerm);
 
       // get the constraint factor
@@ -678,16 +548,13 @@
       tmpConstraintExpression = builder.getConstraintExpression();
       setConstraintExpression(tmpConstraintExpression);
 
-      // log that we're recursing with a constraint factor
       if (logger.isDebugEnabled()) {
         logger.debug("Recursing with constraint factor " + constraintFactor);
         logger.debug("Got: " + tmpConstraintExpression);
       }
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
@@ -699,14 +566,10 @@
    * @param rawConstraintTerm a MINUS constraint dterm.
    */
   public void caseAMinusConstraintDterm(AMinusConstraintDterm rawConstraintTerm) {
-    // TODO
 
     try {
 
-      // log that we've got a MINUS constraint dterm
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found MINUS contraint dterm " + rawConstraintTerm);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Found MINUS contraint dterm " + rawConstraintTerm);
 
       // get the minuend expression
       PConstraintDterm minuendExpr =
@@ -716,24 +579,20 @@
       PConstraintFactor subtrahendExpr =
           ((AMinusConstraintDterm) rawConstraintTerm).getSubtrahend();
 
-      // log that we've found the operands of the subtraction
       if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with minuend " + minuendExpr +
-            " & subtrahend " + subtrahendExpr);
+        logger.debug("Recursing with minuend " + minuendExpr + " & subtrahend " + subtrahendExpr);
       }
 
-      ConstraintExpressionBuilder builder =
-          new ConstraintExpressionBuilder(interpreter);
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
 
       // get the LHS and RHS operands of the conjunction
-      minuendExpr.apply((Switch) builder);
+      minuendExpr.apply((Switch)builder);
       ConstraintExpression minuend = builder.getConstraintExpression();
 
       // Create another constraint builder and assign to RHS.
-      subtrahendExpr.apply((Switch) builder);
+      subtrahendExpr.apply((Switch)builder);
       ConstraintExpression subtrahend = builder.getConstraintExpression();
 
-      // log that we've resolved the operands
       if (logger.isDebugEnabled()) {
         logger.debug("Resolved minuend operand " + minuend);
         logger.debug("Resolved subtrahend operand " + subtrahend);
@@ -741,15 +600,14 @@
 
       // apply the conjunction
       setConstraintExpression(new ConstraintDifference(minuend, subtrahend));
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
     }
   }
 
+
   /**
    * Helper method used to build up a Constraint object from a SableCC
    * PConstraint object.
@@ -761,10 +619,7 @@
   Constraint buildConstraint(PConstraint pconstraint) throws QueryException,
       URISyntaxException {
 
-    // log that we've found a constraint
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found constraint " + pconstraint + ", resolving components");
-    }
+    if (logger.isDebugEnabled()) logger.debug("Found constraint " + pconstraint + ", resolving components");
 
     // get the constraint's components
     ConstraintElement subject =
@@ -774,7 +629,6 @@
     ConstraintElement object =
         toConstraintElement(((AConstraint) pconstraint).getObject());
 
-    // log the components we've found
     if (logger.isDebugEnabled()) {
       logger.debug("Found subject " + subject);
       logger.debug("Found predicate " + predicate);
@@ -782,7 +636,7 @@
     }
 
     // check for an IN - this is illegal
-    if (((AConstraint) pconstraint).getInClause() != null) {
+    if (((AConstraint)pconstraint).getInClause() != null) {
       throw new QueryException("Illegal in clause on transitive constraint.");
     }
 
@@ -790,6 +644,7 @@
     return ConstraintFactory.newConstraint(subject, predicate, object);
   }
 
+
   /**
    * Constructs a {@link org.mulgara.query.ConstraintElement} from a
    * {@link org.mulgara.itql.node.PElement}.
@@ -805,18 +660,12 @@
    *      conform to
    *      <a href="http://www.isi.edu/in-notes/rfc2396.txt">RFC 2396</a>
    */
-  private ConstraintElement toConstraintElement(PElement element) throws
-      QueryException, URISyntaxException {
+  private ConstraintElement toConstraintElement(PElement element) throws QueryException, URISyntaxException {
 
     // validate the element parameter
-    if (element == null) {
-      throw new IllegalArgumentException("Null \"element\" parameter");
-    }
+    if (element == null) throw new IllegalArgumentException("Null \"element\" parameter");
 
-    // log what we're doing
-    if (logger.isDebugEnabled()) {
-      logger.debug("Resolving " + element + "to a constraint element");
-    }
+    if (logger.isDebugEnabled()) logger.debug("Resolving " + element + "to a constraint element");
 
     // create a constraint element to return
     ConstraintElement constraintElement = null;
@@ -828,22 +677,19 @@
       PVariable rawVariable = ((AVariableElement) element).getVariable();
       String variableName = ((AVariable) rawVariable).getIdentifier().getText();
 
-      // log what we're doing
-      if (logger.isDebugEnabled()) {
-        logger.debug("Resolved " + element + " to variable " + variableName);
-      }
+      if (logger.isDebugEnabled()) logger.debug("Resolved " + element + " to variable " + variableName);
 
       // create a new variable
       constraintElement = new Variable(variableName);
-    }
-    else if (element instanceof AResourceElement) {
 
+    } else if (element instanceof AResourceElement) {
+
       // create a new resource
       constraintElement = new URIReferenceImpl(interpreter.toURI(
           ((AResourceElement) element).getResource()));
-    }
-    else if (element instanceof ALiteralElement) {
 
+    } else if (element instanceof ALiteralElement) {
+
       // create a new literal
       constraintElement = interpreter.toLiteralImpl(((ALiteralElement) element).
           getLiteral());

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/HelpPrinter.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/HelpPrinter.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/HelpPrinter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -346,7 +346,7 @@
     helpMsg.append("\nAuthenticates a user." + eol);
     helpMsg.append(eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> su <ldap://bar.org> fred Fo0Bar ;" + eol);
+    helpMsg.append("  TQL> su <ldap://bar.org> fred Fo0Bar ;" + eol);
 
     // return the help mesage
     return helpMsg;
@@ -376,7 +376,7 @@
     helpMsg.append("  o autocommit - automatically commits after each insert" + eol);
     helpMsg.append("  o time - displays command execution time" + eol);
     helpMsg.append(eol + "For example:" + eol + eol);
-    helpMsg.append("  iTQL> set time on ;" + eol);
+    helpMsg.append("  TQL> set time on ;" + eol);
 
     // return the help mesage
     return helpMsg;
@@ -399,7 +399,7 @@
     helpMsg.append("\nExecutes an iTQL script." + eol);
     helpMsg.append(eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> execute " +
+    helpMsg.append("  TQL> execute " +
         "<file:/usr/local/mulgara/sample/itql/loaddc.itql> ;" + eol);
 
     // return the help mesage
@@ -423,9 +423,9 @@
     helpMsg.append("\nCreates an alias to a URL, model or database." + eol);
     helpMsg.append(eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> alias <http://www.w3.org/2000/01/rdf-schema#> as " +
+    helpMsg.append("  TQL> alias <http://www.w3.org/2000/01/rdf-schema#> as " +
         "rdfs ;" + eol);
-    helpMsg.append("  iTQL> select $subj $obj from " +
+    helpMsg.append("  TQL> select $subj $obj from " +
         "<http://purl.org/dc/elements/1.1/> where $subj <rdfs:label> $obj ;" + eol);
 
     // return the help mesage
@@ -449,7 +449,7 @@
     helpMsg.append(eol + "Creates a new (empty) model." + eol);
     helpMsg.append(eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> create <rmi://localhost/foo#bar> ;" + eol);
+    helpMsg.append("  TQL> create <rmi://localhost/foo#bar> ;" + eol);
 
     // return the help mesage
     return helpMsg;
@@ -472,7 +472,7 @@
     helpMsg.append(eol + "Drops a model." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> drop <rmi://localhost/foo#bar> ;" + eol);
+    helpMsg.append("  TQL> drop <rmi://localhost/foo#bar> ;" + eol);
 
     // return the help mesage
     return helpMsg;
@@ -496,7 +496,7 @@
         "query into a model or database." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> insert (<http://purl.org/dc/elements/1.1/subject> " +
+    helpMsg.append("  TQL> insert (<http://purl.org/dc/elements/1.1/subject> " +
         "<http://www.w3.org/2000/01/rdf-schema#label> 'Subject') into " +
         "<rmi://localhost/foo#bar> ;" + eol);
 
@@ -522,7 +522,7 @@
         "query from a model or database." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> delete (<http://purl.org/dc/elements/1.1/subject> " +
+    helpMsg.append("  TQL> delete (<http://purl.org/dc/elements/1.1/subject> " +
         "<http://www.w3.org/2000/01/rdf-schema#label> 'Subject') from " +
         "<rmi://localhost/foo#bar> ;" + eol);
 
@@ -547,11 +547,11 @@
     helpMsg.append("\nLoads the contents of a file into a model." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> load <http://foo.com/bar.rdf> into " +
+    helpMsg.append("  TQL> load <http://foo.com/bar.rdf> into " +
         "<rmi://localhost/foo#bar> ;" + eol);
-    helpMsg.append("  iTQL> load local <file:/c:/data/foo.rdf> into " +
+    helpMsg.append("  TQL> load local <file:/c:/data/foo.rdf> into " +
         "<rmi://localhost/foo#foo> ;" + eol);
-    helpMsg.append("  iTQL> load remote <file:/m:/files/foo.rdf> into " +
+    helpMsg.append("  TQL> load remote <file:/m:/files/foo.rdf> into " +
         "<rmi://localhost/foo#foo> ;" + eol);
     helpMsg.append("" + eol);
     helpMsg.append("'local' refers to the file system on the client" + eol);
@@ -579,9 +579,9 @@
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
     helpMsg.append(
-        "  iTQL> backup <rmi://localhost/server1> to remote <file:/tmp/server1backup> ;" + eol);
+        "  TQL> backup <rmi://localhost/server1> to remote <file:/tmp/server1backup> ;" + eol);
     helpMsg.append(
-        "  iTQL> backup <rmi://localhost/server1#foo> to local <file:/tmp/foo.rdf> ;" + eol);
+        "  TQL> backup <rmi://localhost/server1#foo> to local <file:/tmp/foo.rdf> ;" + eol);
     helpMsg.append("" + eol);
     helpMsg.append("'local' refers to the file system on the client" + eol);
     helpMsg.append("'remote' refers to the file system on the server [default]" + eol);
@@ -609,9 +609,9 @@
         "contents of the file" + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> restore <rmi://localhost/server1> from local " +
+    helpMsg.append("  TQL> restore <rmi://localhost/server1> from local " +
         "<file:/tmp/server1backup> ;" + eol);
-    helpMsg.append("  iTQL> restore <rmi://localhost/server1> from remote " +
+    helpMsg.append("  TQL> restore <rmi://localhost/server1> from remote " +
         "<file:/tmp/server1backup> ;" + eol);
     helpMsg.append("" + eol);
     helpMsg.append("'local' refers to the file system on the client" + eol);
@@ -638,7 +638,7 @@
     helpMsg.append("\nPerforms a query on a set of triples." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> select $subj $obj from " +
+    helpMsg.append("  TQL> select $subj $obj from " +
         "<http://purl.org/dc/elements/1.1/> where $subj <rdfs:label> $obj ;" + eol);
 
     // return the help mesage
@@ -662,7 +662,7 @@
     helpMsg.append("\nCommits a transaction." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> commit ;" + eol);
+    helpMsg.append("  TQL> commit ;" + eol);
 
     // return the help mesage
     return helpMsg;
@@ -685,7 +685,7 @@
     helpMsg.append("\nRolls back changes." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  iTQL> rollback ;" + eol);
+    helpMsg.append("  TQL> rollback ;" + eol);
 
     // return the help mesage
     return helpMsg;
@@ -708,10 +708,10 @@
     helpMsg.append("\nApplies a set of rules." + eol);
     helpMsg.append("" + eol);
     helpMsg.append("For example:" + eol);
-    helpMsg.append("  iTQL> apply <rmi://localhost/server1#krule> to <rmi://localhost/server1#camera>;" + eol);
+    helpMsg.append("  TQL> apply <rmi://localhost/server1#krule> to <rmi://localhost/server1#camera>;" + eol);
     helpMsg.append("This puts entailed statements into <rmi://localhost/server1#camera>" + eol);
     helpMsg.append("Or to put the entailed statements into another model:" + eol);
-    helpMsg.append("  iTQL> apply <rmi://localhost/server1#krule> to <rmi://localhost/server1#camera> <rmi://localhost/server1#entailed>;" + eol);
+    helpMsg.append("  TQL> apply <rmi://localhost/server1#krule> to <rmi://localhost/server1#camera> <rmi://localhost/server1#entailed>;" + eol);
     return helpMsg;
   }
 

Deleted: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,3916 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public License
- * Version 1.1 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- *
- * The Original Code is the Kowari Metadata Store.
- *
- * The Initial Developer of the Original Code is Plugged In Software Pty
- * Ltd (http://www.pisoftware.com, mailto:info at pisoftware.com). Portions
- * created by Plugged In Software Pty Ltd are Copyright (C) 2001,2002
- * Plugged In Software Pty Ltd. All Rights Reserved.
- *
- * Contributor(s):
- *  Copywrite in the anon-variable support:
- *  The Australian Commonwealth Government
- *  Department of Defense
- *  Developed by Netymon Pty Ltd
- *  under contract 4500507038
- *  contributed to the Mulgara Project under the 
- *    Mozilla Public License version 1.1
- *  per clause 4.1.3 and 4.1.4 of the above contract.
- *
- * [NOTE: The text of this Exhibit A may differ slightly from the text
- * of the notices in the Source Code files of the Original Code. You
- * should use the text of this Exhibit A rather than the text found in the
- * Original Code Source Code for Your Modifications.]
- *
- */
-
-package org.mulgara.itql;
-
-// Java 2 standard packages
-import java.io.*;
-import java.net.*;
-import java.util.*;
-import java.rmi.server.UnicastRemoteObject;
-import java.rmi.RemoteException;
-import java.rmi.NoSuchObjectException;
-
-// Third party packages
-import org.apache.log4j.Logger; // Apache Log4J
-import org.jrdf.graph.*; // JRDF
-
-// Locally written packages
-
-// Automatically generated packages (SableCC)
-import org.mulgara.itql.analysis.*;
-import org.mulgara.itql.lexer.*;
-import org.mulgara.itql.node.*;
-import org.mulgara.itql.parser.*;
-import org.mulgara.query.*;
-import org.mulgara.query.rdf.*;
-import org.mulgara.rules.*;
-import org.mulgara.server.NonRemoteSessionException;
-import org.mulgara.server.Session;
-import org.mulgara.server.SessionFactory;
-import org.mulgara.server.driver.SessionFactoryFinder;
-import org.mulgara.server.driver.SessionFactoryFinderException;
-
-// emory util package
-import edu.emory.mathcs.util.remote.io.*;
-import edu.emory.mathcs.util.remote.io.server.impl.*;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.ZipInputStream;
-
-/**
- * Interactive TQL (ITQL) command interpreter.
- * <p>
- * Responsible for the following :
- * - maintains connectivty between client and server;
- * - parsing and converting TQL requests to query objects for execution;
- * - Abstract layer for the {@link ItqlInterpreterBean} and {@link org.mulgara.connection.MulgaraConnection}s.
- * </p>
- *
- * @created 2001-08-21
- * @author Simon Raboczi
- * @author Tom Adams
- * @author Paul Gearon
- * @version $Revision: 1.12 $
- * @modified $Date: 2005/07/03 12:52:07 $ by $Author: pgearon $
- * @maintenanceAuthor $Author: pgearon $
- * @company <a href="mailto:info at PIsoftware.com">Plugged In Software</a>
- * @copyright &copy;2001-2004 <a href="http://www.tucanatech.com/">Tucana Technologies, Inc.</a>
- * @copyright &copy;2005 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlInterpreter extends DepthFirstAdapter {
-
-  //
-  // Constants
-  //
-  /** The rdf namespace prefix. */
-  public static final String RDF = "rdf";
-    
-  /** The rdfs namespace prefix. */
-  public static final String RDFS = "rdfs";
-    
-  /** The owl namespace prefix. */
-  public static final String OWL = "owl";
-    
-  /** The mulgara namespace prefix. */
-  public static final String MULGARA = "mulgara";
-    
-  /** The krule namespace prefix. */
-  public static final String KRULE = "krule";
-    
-  /** The URI of the rdf namespace. */
-  public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
-    
-  /** The URI of the rdfs namespace. */
-  public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#";
-    
-  /** The URI of the owl namespace. */
-  public static final String OWL_NS = "http://www.w3.org/2002/07/owl#";
-    
-  /** The URI of the mulgara namespace. */
-  public static final String MULGARA_NS = "http://mulgara.org/mulgara#";
-    
-  /** The URI of the krule namespace. */
-  public static final String KRULE_NS = "http://mulgara.org/owl/krule/#";
-
-  /**
-   * Get line separator.
-   */
-  private static final String EOL = System.getProperty("line.separator");
-
-  /**
-   * the logger
-   */
-  private static final Logger logger =
-      Logger.getLogger(ItqlInterpreter.class.getName());
-
-  /**
-   * the message to display to the user if no results message was specififed by
-   * a command
-   */
-  private final static String DEFAULT_RESULT_MESSAGE = "No results";
-
-  /**
-   * A constraint expression builder.
-   */
-  private ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(this);
-
-  /**
-   * Variable factory for this interpreter.
-   */
-  private VariableFactory variableFactory = new VariableFactoryImpl();
-
-  /**
-   * Lexer...
-   */
-  Lexer2 lexer = new Lexer2();
-
-  //
-  // Members
-  //
-
-  /**
-   * the driver used to communicate with the database
-   */
-  private Session session = null;
-
-  /**
-   * A session provided by an external source. Also acts as a flag to indicate that
-   * a session has been provided.
-   */
-  private Session providedSession = null;
-
-  /**
-   * the map from targets to aliases
-   */
-  private Map aliasMap = null;
-
-  /**
-   * a flag indicating the user has entered the quit command
-   */
-  private boolean quitRequested = false;
-
-  /**
-   * the last query parsed
-   */
-  private Query lastQuery = null;
-
-  /**
-   * the query should be executed when it has been parsed
-   */
-  private boolean executeQuery = true;
-
-  /**
-   * the results of the last command execution
-   */
-  private Answer lastAnswer = null;
-
-  /**
-   * the results of the last command execution
-   */
-  private String lastMessage = null;
-
-  /**
-   * the results of the last error
-   */
-  private ItqlInterpreterException lastError = null;
-
-  /**
-   * the time a command started
-   */
-  private long commandStartTime = -1L;
-
-  /**
-   * the log file to record all iTQL requests *
-   */
-  private PrintWriter itqlLog = null;
-
-  /**
-   * the location of the log iTQL file
-   */
-  private String itqlLogFile = null;
-
-  /**
-   * Map from security domain URIs to {@link Login} records.
-   */
-  private final Map loginMap = new HashMap();
-
-  /**
-   * The URI of the server of the current {@link #session}.
-   */
-  private URI serverURI = null;
-
-  /**
-   * The security domain for the session factory that produced
-   * {@link #session}.
-   */
-  private URI securityDomainURI = null;
-
-  /**
-   * This will be <code>true</code> if {@link #autoCommit} is
-   * <code>false</code> and the {@link #session} has been {@link #update}d.
-   */
-  private boolean transactionUpdated = false;
-
-  /**
-   * True if we are using a local session.
-   */
-  public boolean isLocal;
-
-  //
-  // Interpreter options
-  //
-
-  /**
-   * the option to automatically make each method call transactional
-   */
-  private boolean autoCommit = true;
-
-  /**
-   * the option to enable the echoing of command output
-   */
-  private boolean echoOption = true;
-
-  /**
-   * the option to enable the display of command statistics
-   */
-  private boolean statisticsOption = false;
-
-  /**
-   * the option to enable the stopping of the interpreter on error in scripts
-   */
-  private boolean stoponerrorOption = false;
-
-  /**
-   * the option to enable the timing of commands
-   */
-  private boolean timeOption = false;
-
-  /**
-   * The next anonymous variable suffix
-   */
-  private int anonSuffix = 0;
-
-  //
-  // Constructors
-  //
-
-  /**
-   * Creates a new ITQL command interpreter.
-   *
-   * @param aliasMap the map from targets to aliases, never <code>null</code>
-   */
-  public ItqlInterpreter(Map aliasMap) {
-
-    // validate aliasMap parameter
-    if (aliasMap == null) {
-      throw new IllegalArgumentException("Null \"alias\" parameter");
-    }
-
-    // set members
-    this.setAliasMap(aliasMap);
-    this.setQuitRequested(false);
-
-    // log the creation of this interpreter
-    if (logger.isDebugEnabled()) {
-      logger.debug("Itql interpreter created");
-    }
-
-    // is this session configured for logging.
-    if (System.getProperty("itql.command.log") != null) {
-      itqlLogFile = System.getProperty("itql.command.log");
-      logger.info("iTQL command logging has been enabled.  Logging to " + System.getProperty("itql.command.log"));
-    }
-  }
-
-  /**
-   * Constructor internal to Mulgara that accepts a provided session.
-   *
-   * @param providedSession The session to use.
-   * @param aliasMap the map from targets to aliases, never <code>null</code>
-   */
-  public ItqlInterpreter(Session providedSession, Map aliasMap) {
-    this(aliasMap);
-    // validate providedSession parameter
-    if (providedSession == null) {
-      throw new IllegalArgumentException("Null session parameter");
-    }
-
-    this.providedSession = providedSession;
-    this.session = providedSession;
-  }
-
-
-  /**   
-   * Set up default aliases.
-   *
-   * @return A map of aliases to their fully qualified names
-   */        
-  public static Map getDefaultAliases() {
-    Map aliases = new HashMap();
-    try {     
-      aliases.put(RDF, new URI(RDF_NS));
-      aliases.put(RDFS, new URI(RDFS_NS));
-      aliases.put(OWL, new URI(OWL_NS));
-      aliases.put(MULGARA, new URI(MULGARA_NS));
-      aliases.put(KRULE, new URI(KRULE_NS));
-    } catch (URISyntaxException e) {
-      /* get those aliases which we could */
-      logger.error("Error defining internal aliases: ", e);
-    }
-    return aliases;
-  }  
-
-
-  /**
-   * @return whether there are unparsed tokens from an unterminated command
-   */
-  public boolean isComplete() {
-
-    return lexer.leftoverTokenList.size() == 0;
-  }
-
-  /**
-   * Returns true if a quit command has been entered. <p>
-   *
-   * Note. This method will return true after a quit command has been issued. It
-   * is up to the user of this class to check for a quit after each command has
-   * been issued, eg. </p> <pre>
-   * while (!interpreter.isQuitRequested()) {
-   *   String result = interpreter.executeCommand(command);
-   * }
-   * </pre>
-   *
-   * @return true if a quit command has been entered
-   */
-  public boolean isQuitRequested() {
-
-    return this.quitRequested;
-  }
-
-  // toNode()
-
-  /**
-   * Returns the Exception Chain in a pretty fashion.
-   *
-   * @param e the throwable exception
-   * @param preferredDepth the preferred depth to go into the exception to
-   *   retrieve the root cause.  A depth of zero will chain all exceptions
-   *   together.
-   * @return String the Exception Chain in a pretty fashion
-   */
-  public String getCause(Throwable e, int preferredDepth) {
-
-    // Keep getting the cause of the message until we reach preferred depth or
-    // null cause.
-    Throwable preferredException = e;
-    int index = 0;
-    while ( (preferredException != null) && (index != preferredDepth)) {
-
-      // Pre-check next exception and increment index if it's not null.
-      if (preferredException.getCause() != null) {
-
-        index++;
-      }
-
-      // Get next exception
-      preferredException = preferredException.getCause();
-    }
-
-    // If the preferredException is not null.
-    if (preferredException != null) {
-
-      e = preferredException;
-    }
-
-    // get the exception's message
-    String message = e.getMessage();
-
-    // we don't want nulls
-    if (message == null) {
-
-      message = "";
-    }
-
-    // end if
-    // get the cause of the exception
-    Throwable cause = e.getCause();
-
-    // decend into it if we can
-    if (cause != null) {
-
-      // get the cause's message
-      String causeMsg = this.getCause(cause, 0);
-
-      // only add the cause's message if there was one
-      if (causeMsg != null) {
-
-        // format the class name
-        String exceptionClassName = cause.getClass().getName();
-        exceptionClassName =
-            exceptionClassName.substring(exceptionClassName.lastIndexOf('.') +
-                                         1);
-        message += (EOL + "Caused by: (" + exceptionClassName + ") " +
-                    causeMsg);
-      }
-
-      // end if
-    }
-
-    // end if
-    // return the message
-    return message;
-  }
-
-  /**
-   * Returns the error of the last query. Methods overriding {@link
-   * org.mulgara.itql.analysis.DepthFirstAdapter} are expected to set a
-   * results message, even if that message is null.  The is for APIs, logging
-   * and programmers not for users.
-   *
-   * @return the error of the last query, <code>null</code> if the query did not
-   *      fail
-   * @see #setLastError(Exception)
-   */
-  public ItqlInterpreterException getLastError() {
-
-    return this.lastError;
-  }
-
-  /**
-   * Returns the results of the last query. Methods overriding {@link
-   * org.mulgara.itql.analysis.DepthFirstAdapter} are expected to set a
-   * results message, even if that message is null.
-   *
-   * @return the results of the last query, <code>null</code> if the query
-   *      failed
-   * @see #setLastAnswer(Answer)
-   */
-  public Answer getLastAnswer() {
-    return this.lastAnswer;
-  }
-
-  /**
-   * Returns the results of the last command execution. Methods overriding
-   * {@link org.mulgara.itql.analysis.DepthFirstAdapter} are expected to set
-   * a results message, even if that message is null.  This is the user
-   * understandable message.
-   *
-   * @return the results of the last command execution, null if the command did
-   *      not set any message
-   * @see #setLastMessage(String)
-   */
-  public String getLastMessage() {
-
-    return this.lastMessage;
-  }
-
-  // ItqlInterpreter()
-  //
-  // Public API
-  //
-
-  /**
-   * Executes the given ITQL command.
-   *
-   * @param command the command to execute in ITQL syntax
-   * @throws ParserException if the syntax of the command is incorrect
-   * @throws LexerException if the syntax of the command is incorrect
-   * @throws IOException if the <var>command</var> cannot be paersed
-   * @throws IllegalArgumentException if the <var>command</var> is
-   *   <code>null</code>
-   */
-  public void executeCommand(String command) throws ParserException,
-      LexerException, Exception {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // validate command parameter
-    if ((command == null) || command.equals("")) {
-      throw new IllegalArgumentException("Null \"command\" parameter");
-    } // end if
-
-    // log that we're going to execute the command
-    if (logger.isDebugEnabled()) {
-      logger.debug("Executing command " + command);
-    }
-
-    // log the iTQL command - system property itql.command.log must be set
-    this.logItql(command);
-
-    // Reset the variable incrementer in the query.
-    variableFactory.reset();
-
-    // push the command into the lexer
-    lexer.add(command);
-
-    // if the lexer saw terminators, parse the associated commands
-    while (lexer.nextCommand()) {
-
-      Start commandTree = null;
-
-      // parse the command
-      try {
-        Parser parser = new Parser(lexer);
-        commandTree = parser.parse();
-      }
-      catch (ParserException pe) {
-
-        // let the user know the problem
-        this.setLastError(pe);
-        this.setLastAnswer(null);
-        this.setLastMessage("Syntax error " + EOL + this.getCause(pe, 2));
-        flush();
-        throw pe;
-      }
-      catch (LexerException le) {
-
-        // let the user know the problem
-        this.setLastError(le);
-        this.setLastAnswer(null);
-        this.setLastMessage("Lexer exception " + EOL + this.getCause(le, 2));
-        flush();
-        throw le;
-      }
-
-      // execute the command
-      try {
-        commandTree.apply(this);
-      }
-      catch (Exception e) {
-        flush();
-        throw e;
-      }
-      catch (Error e) {
-
-        flush();
-        throw e;
-      }
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Successfully executed command " + command);
-      }
-    }
-  }
-
-  /**
-   * Discard any unparsed tokens.
-   *
-   */
-  public void flush() {
-
-    lexer.leftoverTokenList.clear();
-  }
-
-  // isQuitRequested()
-
-  /**
-   * Parse a string into a {@link Query}.
-   *
-   * @param queryString a string containing an ITQL query
-   * @return the corresponding {@link Query} instance
-   * @throws IOException if <var>queryString</var> can't be buffered.
-   * @throws LexerException if <var>queryString</var> can't be tokenized.
-   * @throws ParserException if <var>queryString</var> is not syntactic.
-   */
-  public Query parseQuery(String queryString) throws IOException,
-      LexerException, ParserException {
-
-    if (queryString == null) {
-      throw new IllegalArgumentException("Null \"queryString\" parameter");
-    }
-
-    // clean up query
-    queryString = queryString.trim();
-    while (queryString.endsWith(";")) {
-      queryString = queryString.substring(0, queryString.length() - 1);
-    }
-
-    // log that we're going to execute the command
-    if (logger.isDebugEnabled()) {
-      logger.debug("Parsing query \"" + queryString + "\"");
-    }
-
-    // execute the command
-    Parser parser = new Parser(new Lexer(new PushbackReader(new StringReader(queryString), 256)));
-    lastQuery = null;
-    try {
-      executeQuery = false;
-      parser.parse().apply(this);
-    }
-    finally {
-      executeQuery = true;
-    }
-
-    if (lastQuery == null) {
-      throw new ParserException(null, "Parameter was not a query");
-    }
-
-    // return the results of the command
-    return lastQuery;
-  }
-
-
-  //
-  // Methods overridden from DepthFirstAdapter
-  //
-
-  /**
-   * Hijacks the start of every command to perform actions on interpreter
-   * options.
-   *
-   * @param node a command to be executed by the interpreter
-   */
-  public void inACommandStart(ACommandStart node) {
-
-    // set the time of the start of the command
-    this.setCommandStartTime(System.currentTimeMillis());
-  }
-
-  // inACommandStart()
-
-  /**
-   * Load the contents of an InputStream into a database/model.  The method assumes
-   * the source to be RDF/XML.
-   *
-   * @param inputStream a locally supplied inputstream.
-   * @param destinationURI destination model for the source data
-   * @return number of rows inserted into the destination model
-   * @throws QueryException if the data fails to load
-   */
-  public long load(InputStream inputStream, URI destinationURI)
-                throws QueryException {
-
-     if ( inputStream == null ) {
-       throw new IllegalArgumentException("Null InputStream supplied");
-     }
-     if ( destinationURI == null ) {
-       throw new IllegalArgumentException("Null destination URI supplied");
-     }
-
-     URI dummySourceURI = null;
-     try {
-
-       // create dummy URI to force the server to assume RDF/XML inputStream
-       dummySourceURI = new URI(Mulgara.NAMESPACE+"locally-sourced-inputStream.rdf");
-
-      } catch ( URISyntaxException ex ) {};
-
-      return this.load(inputStream, dummySourceURI, destinationURI);
-
-   }
-
-  /**
-   * Load the contents of an InputStream or a URI into a database/model.
-   *
-   * @param inputStream a locally supplied inputstream.  Null assumes the
-   * server will obtain the stream from the sourceURI.
-   * @param sourceURI an idenifier for the source or inputstream.  The extension
-   * will determine the type of parser to be used. ie. .rdf or .n3  When an inputStream
-   * is supplied the server will not attempt to read the contents of the sourceURI
-   * @param destinationURI destination model for the source data
-   * @return number of rows inserted into the destination model
-   * @throws QueryException if the data fails to load
-   */
-  public long load(InputStream inputStream, URI sourceURI, URI destinationURI)
-                throws QueryException {
-
-    RemoteInputStreamSrvImpl srv = null;
-
-    if ( sourceURI == null ) {
-      throw new IllegalArgumentException("Null source URI supplied");
-    }
-    if ( destinationURI == null ) {
-      throw new IllegalArgumentException("Null destination URI supplied");
-    }
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Loading "+sourceURI+" into " +destinationURI );
-    }
-
-    long stmtCount = 0;
-
-    // update the session
-    this.updateSession(new ModelResource(destinationURI));
-
-    if ( inputStream != null ) {
-
-      //is the file/stream compressed?
-      try {
-        String path = (sourceURI == null) ? "" : sourceURI.toString();
-        inputStream = adjustForCompression(path, inputStream);
-      } catch (IOException ioException) {
-
-        throw new QueryException("Could not get InputStream for compressed file.",
-            ioException);
-      }
-
-      // open and wrap the inputstream
-      srv = new RemoteInputStreamSrvImpl(inputStream);
-
-      try {
-
-        // prepare it for exporting
-        UnicastRemoteObject.exportObject(srv);
-
-      } catch ( RemoteException rex ) {
-        throw new QueryException("Unable to create a remote InputStream to "+
-                                 "load statements into "+ destinationURI, rex);
-      }
-
-      inputStream = new RemoteInputStream(srv);
-    }
-
-    try {
-      stmtCount =
-        this.getSession().setModel( inputStream,
-                                    destinationURI, // model to redefine
-                                    new ModelResource(sourceURI));
-    } finally {
-      if ( srv != null ) {
-        try {
-          UnicastRemoteObject.unexportObject(srv, false);
-        } catch ( NoSuchObjectException ex ) {};
-      }
-    }
-    update();
-
-    // log that we've loaded the contents of the file
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Loaded " + stmtCount + " statements from " + sourceURI +
-                   " into " + destinationURI);
-    }
-
-    // tell the user
-    if (stmtCount > 0L) {
-
-      this.setLastMessage("Successfully loaded " + stmtCount +
-                          " statements from " + sourceURI + " into " +
-                          destinationURI);
-    }
-    else {
-
-      this.setLastMessage("WARNING: No valid RDF statements found in " +
-                          sourceURI);
-    } // end if
-
-    return stmtCount;
-
-  }
-
-  /**
-   * Backup all the data on the specified server or model to a local file.
-   * The database is not changed by this method.
-   *
-   * @param sourceURI The URI of the server or model to backup.
-   * @param destinationFile an non-existent file on the local file system to
-   * receive the backup contents.
-   * @throws QueryException if the backup cannot be completed.
-   */
-  public void backup(URI sourceURI, File destinationFile )
-    throws QueryException {
-
-    FileOutputStream fileOutputStream = null;
-    try {
-
-      fileOutputStream = new FileOutputStream(destinationFile);
-    }
-    catch (FileNotFoundException ex) {
-      throw new QueryException("File "+destinationFile+" cannot be created "+
-                           "for backup. ", ex);
-    }
-
-    this.backup( sourceURI, fileOutputStream  );
-
-    // assume the server may not have closed the file.
-    if ( fileOutputStream != null) {
-      try {
-        fileOutputStream .close();
-      } catch (IOException ioe ) {};
-    }
-  }
-
-  /**
-   * Backup all the data on the specified server to an output stream.
-   * The database is not changed by this method.
-   *
-   * @param sourceURI The URI of the server or model to backup.
-   * @param outputStream The stream to receive the contents
-   * @throws QueryException if the backup cannot be completed.
-   */
-  public void backup(URI sourceURI, OutputStream outputStream)
-    throws QueryException {
-
-     // open and wrap the outputstream
-     RemoteOutputStreamSrvImpl srv = new RemoteOutputStreamSrvImpl(outputStream);
-
-     // prepare it for exporting
-     try {
-       UnicastRemoteObject.exportObject(srv);
-     }
-     catch (RemoteException rex) {
-       throw new QueryException("Unable to backup "+serverURI + " to "+
-                                "an output stream", rex);
-     }
-
-     outputStream = new RemoteOutputStream(srv);
-
-     // set the server URI given a possible model
-     this.setBackupServer( sourceURI );
-
-     try {
-       // perform the backup
-       this.getSession().backup( sourceURI, outputStream );
-
-     } finally {
-       if ( outputStream != null) {
-         try {
-           outputStream.close();
-         } catch (IOException ioe ) {};
-       }
-       if ( srv != null ) {
-         try {
-           UnicastRemoteObject.unexportObject(srv, false);
-         } catch ( NoSuchObjectException ex ) {};
-       }
-     }
-     if ( outputStream != null) {
-       try {
-         outputStream.close();
-       } catch (IOException ioe ) {};
-     }
-  }
-
-  /**
-   * Restore all the data on the specified server. If the database is not
-   * currently empty then the database will contain the union of its current
-   * content and the content of the backup file when this method returns.
-   *
-   * @param inputStream A stream to obtain the restore from.
-   * @param serverURI The URI of the server to restore.
-   * @throws QueryException if the restore cannot be completed.
-   */
-  public void restore(InputStream inputStream, URI serverURI) throws QueryException {
-
-    if ( inputStream == null ) {
-      throw new IllegalArgumentException("Null input stream supplied");
-    }
-    if ( serverURI == null ) {
-      throw new IllegalArgumentException("Null server URI supplied");
-    }
-
-    URI dummySourceURI = null;
-    try {
-
-      // create dummy URI for server identification messages
-      dummySourceURI = new URI(Mulgara.NAMESPACE+"locally-sourced-inputStream.gz");
-
-     } catch ( URISyntaxException ex ) {};
-
-     this.restore(inputStream, dummySourceURI, serverURI);
-
-  }
-
-  /**
-   * Restore all the data on the specified server. If the database is not
-   * currently empty then the database will contain the union of its current
-   * content and the content of the backup file when this method returns.
-   *
-   * @param inputStream a client supplied inputStream to obtain the restore
-   *        content from. If null assume the sourceURI has been supplied.
-   * @param serverURI The URI of the server to restore.
-   * @param sourceURI The URI of the backup file to restore from.
-   * @throws QueryException if the restore cannot be completed.
-   */
-  public void restore(InputStream inputStream, URI serverURI, URI sourceURI)
-      throws QueryException {
-
-    RemoteInputStreamSrvImpl srv = null;
-
-    if ( sourceURI == null ) {
-      throw new IllegalArgumentException("Null source URI supplied");
-    }
-    if ( serverURI == null ) {
-      throw new IllegalArgumentException("Null server URI supplied");
-    }
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Restoring "+sourceURI+" into " +serverURI );
-    }
-
-    // update the session
-    this.updateSession(new ModelResource(serverURI));
-
-    if ( inputStream != null ) {
-
-      // open and wrap the inputstream
-      srv = new RemoteInputStreamSrvImpl(inputStream);
-
-      try {
-
-        // prepare it for exporting
-        UnicastRemoteObject.exportObject(srv);
-
-      } catch ( RemoteException rex ) {
-        throw new QueryException("Unable to restore an remote InputStream "+
-                                 "into "+ serverURI, rex);
-      }
-
-      inputStream = new RemoteInputStream(srv);
-    }
-
-    try  {
-
-      // perform the restore
-      this.getSession().restore( inputStream, serverURI, sourceURI);
-
-    } finally {
-      if ( srv != null ) {
-        try {
-          UnicastRemoteObject.unexportObject(srv, false);
-        } catch ( NoSuchObjectException ex ) {};
-      }
-    }
-
-    update();
-
-    // log that we've loaded the contents of the file
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Restored statements from " + sourceURI +
-                   " into " + serverURI);
-    }
-  }
-
-
-  /**
-   * Hijacks the completion of every command to perform actions on interpreter
-   * options.
-   *
-   * @param node a command to be executed by the interpreter
-   */
-  public void outACommandStart(ACommandStart node) {
-
-    // hijack the last message to return the command time
-    if (this.getTimeOption()) {
-
-      // get the time the command took to execute
-      long commandTimeMillis =
-          System.currentTimeMillis() - this.getCommandStartTime();
-
-      // convert the time to seconds
-      double commandTimeSeconds =
-          ( (double) commandTimeMillis) / ( (double) 1000L);
-
-      // set a new message
-      String commandTimeMsg = EOL + "Command execution time - " +
-          commandTimeSeconds + " seconds";
-      this.setLastMessage(this.getLastMessage() + commandTimeMsg);
-    }
-
-    // end if
-  }
-
-  // outACommandStart()
-
-  /**
-   * Displays help information to the user.
-   *
-   * @param node the help command
-   */
-  public void outAHelpCommand(AHelpCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing help command " + node);
-    }
-
-    // let the user know the help for the selected command
-    this.setLastMessage(HelpPrinter.getHelp(node.getCommandPrefix()));
-  }
-
-  // outAHelpCommand()
-
-  /**
-   * Quits a session.
-   *
-   * @param node the quit command
-   */
-  public void outAQuitCommand(AQuitCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-      logger.debug("Processing quit command " + node);
-    }
-
-    // idicate that a quit command was received
-    this.setQuitRequested(true);
-
-    // let the user know that we're closing down
-    this.setLastMessage("Quitting ITQL session");
-  }
-
-  // outAQuitCommand()
-
-  /**
-   * Commits a transaction.
-   *
-   * @param node the commit command
-   */
-  public void outACommitCommand(ACommitCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing commit command " + node);
-    }
-
-    try {
-
-      // commit this transaction
-      this.getSession().commit();
-
-      // log that we've executed the query
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Successfully committed transaction");
-      }
-
-      // inform the user of the result
-      this.setLastAnswer(null);
-      this.setLastMessage("Successfully committed transaction");
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Unable to commit transaction." + EOL +
-                          this.getCause(qe, 2));
-      logger.warn("Unable to commit transaction", qe);
-    }
-    catch (RuntimeException re) {
-
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Failed to commit transaction:" + this.getCause(re, 0));
-      logger.fatal("Failed to commit transaction", re);
-    }
-
-    // try-catch
-  }
-
-  // outAQuitCommand()
-
-  /**
-   * Rolls back a transaction.
-   *
-   * @param node the rollback command
-   */
-  public void outARollbackCommand(ARollbackCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing rollback command " + node);
-    }
-
-    try {
-
-      // rollback any changes made
-      this.getSession().rollback();
-
-      // log that we've executed the query
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Successfully rolled back changes");
-      }
-
-      // inform the user of the result
-      this.setLastAnswer(null);
-      this.setLastMessage("Successfully rolled back changes");
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Unable to roll back changes." + EOL +
-                          this.getCause(qe, 2));
-      logger.warn("Unable to roll back changes", qe);
-    }
-    catch (RuntimeException re) {
-
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Unable to roll back changes:" + this.getCause(re, 0));
-      logger.fatal("Failed to roll back changes", re);
-    }
-  }
-
-  /**
-   * Executes a query.
-   *
-   * @param node the query command
-   */
-  public void outASelectCommand(ASelectCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-      logger.debug("Processing select command " + node);
-    }
-
-    try {
-
-      // build the query
-      Query query = this.buildQuery(node.getQuery());
-
-      if (executeQuery) {
-
-        // log that we've created the query and will execute it
-        if (logger.isDebugEnabled()) {
-          logger.debug("Executing query " + query);
-          logger.debug("Executing query " + query.getVariableList());
-        }
-
-        updateSession(query.getModelExpression());
-
-        // build the query
-        Answer answer = this.getSession().query(query);
-
-        // make sure we got an answer
-        if (answer == null) {
-          throw new QueryException("Invalid answer received");
-        } // end if
-
-        // log that we've executed the query
-        if (logger.isDebugEnabled()) {
-          logger.debug("Successfully executed query " + node);
-        }
-
-        // move to the first row
-        answer.beforeFirst();
-
-        // inform the user of the answer
-        this.setLastAnswer(answer);
-      }
-    }
-    catch (TuplesException te) {
-
-      // let the user know the problem
-      this.setLastError(te);
-      this.setLastAnswer(null);
-      this.setLastMessage("Couldn't answer select query." + EOL + this.getCause(te, 2) + EOL + te);
-      logger.warn("Couldn't answer query", te);
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Couldn't answer select query." + EOL + this.getCause(qe, 2) + EOL + qe);
-      logger.warn("Couldn't answer query", qe);
-    }
-    catch (URISyntaxException use) {
-
-      // let the user know the problem
-      this.setLastError(use);
-      this.setLastAnswer(null);
-      this.setLastMessage("Couldn't answer query: Invalid resource URI.");
-      logger.warn("Invalid resource URI." + EOL + this.getCause(use, 0));
-    }
-    catch (RuntimeException re) {
-
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Couldn't answer query :" + this.getCause(re, 0));
-      logger.fatal("Failed to select statements", re);
-    }
-
-    // try-catch
-  }
-
-  // outASelectCommand()
-
-  /**
-   * Notify that the current session has been updated.
-   */
-  private void update() {
-    transactionUpdated = !autoCommit;
-  }
-
-  /**
-   * If the <code>FROM</code> clause of query refers to models in a different
-   * server than the one we're pointed at, change the {@link #session}.
-   *
-   * @param modelExpression a <code>FROM</code> clause, never <code>null</code>
-   * @throws QueryException if the <var>modelExpression</var> can't be resolved
-   *   by any single server
-   */
-  private void updateSession(ModelExpression modelExpression) throws
-      QueryException {
-    assert modelExpression != null;
-
-    if (providedSession != null) {
-      session = providedSession;
-      return;
-    }
-
-    URI databaseURI = null;
-
-    // Check to see that we're aimed at the right server
-    Set databaseURISet = modelExpression.getDatabaseURIs();
-    assert databaseURISet != null;
-    if (logger.isDebugEnabled()) {
-      logger.debug(
-          "Current server is " + serverURI + ", updating for " + databaseURISet
-          );
-    }
-    switch (databaseURISet.size()) {
-      case 0:
-
-        // Query presumably contains only URLs -- any server can deal with
-        // this, including the current one
-        if (session == null) {
-          try {
-            serverURI = SessionFactoryFinder.findServerURI();
-
-            SessionFactory sessionFactory =
-                SessionFactoryFinder.newSessionFactory(serverURI, !isLocal);
-
-            // Switch the underlying session to point at the required server
-            setSession(sessionFactory.newSession(),
-                       sessionFactory.getSecurityDomain());
-          }
-          catch (SessionFactoryFinderException e) {
-            throw new QueryException("Unable to connect to a server", e);
-          }
-          catch (NonRemoteSessionException e) {
-            throw new QueryException("Error connecting to the local server", e);
-          }
-        }
-        assert session != null;
-        break;
-
-      case 1:
-
-        // Query must go to a particular server
-        databaseURI = (URI) databaseURISet.iterator().next();
-        assert databaseURI != null;
-        if (!databaseURI.equals(serverURI)) {
-          setServerURI(databaseURI);
-        }
-        assert databaseURI.equals(serverURI);
-        break;
-
-      default:
-
-        // Query must be distributed between multiple servers
-        assert databaseURISet.size() > 1;
-
-        if (!databaseURISet.contains(serverURI)) {
-          // We're not even aimed at one of the servers involved in this query,
-          // so choose one arbitrarily and switch to it
-          databaseURI = (URI) databaseURISet.iterator().next();
-          assert databaseURI != null;
-          setServerURI(databaseURI);
-          assert databaseURI.equals(serverURI);
-        }
-
-        // We're now connected to one of the servers involved in this query.
-        assert databaseURISet.contains(serverURI);
-        break;
-    }
-  }
-
-  public void setServerURI(URI databaseURI) throws QueryException {
-
-    // Short-circuit evaluation if the new value equals the old value
-    if (serverURI == null) {
-      if (databaseURI == null) {
-        return;
-      }
-    }
-    else {
-      if (serverURI.equals(databaseURI)) {
-        return;
-      }
-    }
-
-    if (logger.isDebugEnabled()) {
-      logger.debug("Changing server URI from " + serverURI + " to " +
-                   databaseURI);
-    }
-
-    // connect to local server via EmbeddedMulgaraServer Database which is an instance of SessionFactory
-    // - get a session factory from that singleton database
-    // Switch the underlying session to point at the required server
-    if (databaseURI == null) {
-      setSession(null, null);
-    }
-    else {
-      if (providedSession != null) {
-        if (session != providedSession) {
-          session = providedSession;
-        }
-      } else {
-        try {
-          if (logger.isDebugEnabled()) {
-            logger.debug("Finding session factory for " + databaseURI);
-          }
-
-          SessionFactory sessionFactory =
-              SessionFactoryFinder.newSessionFactory(databaseURI, !isLocal);
-
-          if (logger.isDebugEnabled()) {
-            logger.debug("Found " + sessionFactory.getClass() +
-                         " session factory, obtaining session with " +
-                         databaseURI);
-          }
-
-          Session session = sessionFactory.newSession();
-
-          if (logger.isDebugEnabled()) {
-            logger.debug("Obtained session with " + databaseURI);
-          }
-
-          setSession(session, sessionFactory.getSecurityDomain());
-        }
-        catch (SessionFactoryFinderException e) {
-          throw new QueryException("Unable to reconnect to " + databaseURI, e);
-        }
-        catch (NonRemoteSessionException e) {
-          throw new QueryException("Error connecting to the local server", e);
-        }
-      }
-    }
-
-    if (logger.isDebugEnabled()) {
-      logger.debug("Changed server URI from " + serverURI + " to " +
-                   databaseURI);
-    }
-
-    serverURI = databaseURI;
-  }
-
-  /**
-   * Returns the session to use to communicate with the specified Mulgara server.
-   *
-   * @param serverURI URI Server to get a Session for.
-   * @return the session to use to communicate with the specified Mulgara server
-   */
-  public Session getSession(URI serverURI) throws QueryException {
-
-    //set up session to the server
-    this.updateSession(new ModelResource(serverURI));
-    return this.getSession();
-  }
-
-  /**
-   * Substitutes the user associated with this session.
-   *
-   * @param node the su command
-   */
-  public void outASuCommand(ASuCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing su command " + node);
-    }
-
-    URI newSecurityDomainURI = toURI(node.getResource());
-
-    loginMap.put(newSecurityDomainURI,
-                 new Login(node.getUser().getText(),
-                           node.getPassword().getText().toCharArray()));
-
-    if (newSecurityDomainURI.equals(securityDomainURI)) {
-      try {
-        this.getSession().login(securityDomainURI,
-                                node.getUser().getText(),
-                                node.getPassword().getText().toCharArray());
-      }
-      catch (QueryException e) {
-        this.setLastError(e);
-        this.setLastMessage("Could not present credential to " +
-                            securityDomainURI + ": " + e.getMessage());
-      }
-    }
-
-    this.setLastMessage("Credential presented");
-
-  } // outASuCommand()
-
-  /**
-   * Associates an alias prefix with a target.
-   *
-   * @param node the alias command
-   */
-  public void outAAliasCommand(AAliasCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing alias command " + node);
-    }
-
-    // get the prefix and target
-    String aliasPrefix = node.getPrefix().getText();
-    String aliasTarget = node.getTarget().getText();
-
-    try {
-
-      // convert the target to a URI
-      URI aliasTargetURI = new URI(aliasTarget);
-
-      // log the conversion
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Converted " + aliasTarget + " to URI " + aliasTargetURI);
-      }
-
-      // add the alias pair to the map
-      this.addAliasPair(aliasPrefix, aliasTargetURI);
-
-      // log that we've added the pair to the map
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Aliased " + aliasTarget + " as " + aliasPrefix);
-      }
-
-      // tell the user
-      this.setLastMessage("Successfully aliased " + aliasTarget + " as " +
-                          aliasPrefix);
-    }
-    catch (URISyntaxException use) {
-
-      // log the failed URI creation
-      logger.warn("Unable to create URI from alias target " + aliasTarget);
-      this.setLastMessage(aliasTarget + " is not a valid URI");
-      this.setLastError(use);
-      this.setLastAnswer(null);
-    }
-
-    // try-catch
-  }
-
-  // outAAliasCommand()
-
-  /**
-   * Applies a set of rules in a model to data in another model.
-   *
-   * @param node the alias command
-   */
-  public void outAApplyCommand(AApplyCommand node) {
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-      logger.debug("Processing apply command " + node);
-    }
-
-    // get the rule model and target model
-    URI ruleModel = toURI(node.getRules());
-    URI baseModel = toURI(node.getBase());
-    Token dest = node.getDestination();
-    URI destModel = (dest == null) ? baseModel : toURI(dest);
-
-    try {
-      // update the session
-      this.updateSession(new ModelResource(ruleModel));
-
-      // get the structure from the rule model
-      RulesRef rules = this.getSession().buildRules(ruleModel, baseModel, destModel);
-
-      // move the session on to the target
-      this.updateSession(new ModelResource(destModel));
-
-      // create the model
-      this.getSession().applyRules(rules);
-      update();
-
-      this.setLastMessage("Successfully applied " + ruleModel +
-                          " to " + baseModel + (dest == null ? "" : " => " + destModel));
-
-    } catch (Exception e) {
-
-      // let the user know the problem
-      this.setLastError(e);
-      this.setLastAnswer(null);
-      int depth = (e instanceof QueryException) ? 2 : 0;
-      this.setLastMessage("Could not run " + ruleModel + " on " + baseModel + EOL +
-                          this.getCause(e, depth));
-      if (e instanceof QueryException) {
-        logger.warn("Failed to run " + ruleModel + " on " + baseModel, e);
-      } else {
-        logger.fatal("Failed to run rules:", e);
-      }
-    }
-
-  }
-
-  /**
-   * Creates a new database/model.
-   *
-   * @param node the create command
-   */
-  public void outACreateCommand(ACreateCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing create command " + node);
-    }
-
-    // get the name of the model to create
-    URI modelURI = toURI(node.getModel());
-
-    // get the type of model to create; default to mulgara:Model is unspecified
-    URI modelTypeURI = (node.getModelType() == null)
-        ? Session.MULGARA_MODEL_URI
-        : toURI(node.getModelType());
-
-    try {
-
-      // log that we're asking the driver to create the resource
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Creating new model " + modelURI);
-      }
-
-      modelURI = getCanonicalUriAlias(modelURI);
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Model is alias for " + modelURI);
-      }
-
-      // ensure that we're aimed at the server this model will reside upon
-      this.updateSession(new ModelResource(modelURI));
-
-      // create the model
-      this.getSession().createModel(modelURI, modelTypeURI);
-      update();
-
-      // log that we've created the database
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Created new model " + modelURI + " of type " +
-                     modelTypeURI);
-      }
-
-      // tell the user
-      this.setLastMessage("Successfully created model " + modelURI);
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not create " + modelURI + EOL +
-                          this.getCause(qe, 2));
-      logger.warn("Failed to create " + modelURI + " as type " + modelTypeURI,
-                  qe);
-    }
-    catch (RuntimeException re) {
-
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Failed to create model:" + this.getCause(re, 0));
-      logger.fatal("Failed to create model", re);
-    }
-
-    // try-catch
-  }
-
-  // outACreateCommand()
-
-  /**
-   * Drop (delete) a database/model.
-   *
-   * @param node the drop command
-   */
-  public void outADropCommand(ADropCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing drop command " + node);
-    }
-
-    // get the name of the database/model to drop
-    URI resourceURI = toURI(node.getResource());
-
-    try {
-      // ensure we have a session to the server where the model resides
-      this.updateSession(new ModelResource(resourceURI));
-
-      // drop the resource
-      this.getSession().removeModel(resourceURI);
-      update();
-
-      // log that we've dropped the database
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Dropped model " + resourceURI);
-      }
-
-      // tell the user
-      this.setLastMessage("Successfully dropped model " + resourceURI);
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not remove " + resourceURI + EOL +
-                          this.getCause(qe, 2));
-      logger.warn("Failed to remove " + resourceURI, qe);
-    }
-    catch (RuntimeException re) {
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Failed to remove model:" + this.getCause(re, 0));
-      logger.fatal("Failed to remove model", re);
-    }
-
-    // try-catch
-  }
-
-  // outADropCommand()
-
-  /**
-   * Load the contents of a file into a database/model.
-   *
-   * @param node the load command
-   */
-  public void outALoadCommand(ALoadCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    RemoteInputStream remoteInputStream = null;
-    RemoteInputStreamSrvImpl srv = null;
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing load command " + node);
-    }
-
-    // get constituents of the load command
-    URI sourceURI = toURI(node.getSource());
-    URI destinationURI = toURI(node.getDestination());
-
-    try {
-
-      long stmtCount = 0;
-
-      // update the session
-      this.updateSession(new ModelResource(destinationURI));
-
-
-      // are we loading the file locally from the client?
-      if ( node.getLocality() != null &&
-           (node.getLocality() instanceof ALocalLocality) ) {
-
-        if ( logger.isInfoEnabled() ) {
-          logger.info("loading local resource : " + sourceURI );
-        }
-
-        try {
-
-          //open an InputStream
-          InputStream inputStream = sourceURI.toURL().openStream();
-
-          //is the file/stream compressed?
-          String path = (sourceURI == null) ? "" : sourceURI.toString();
-          inputStream = adjustForCompression(path, inputStream);
-
-          // open and wrap the inputstream
-          srv = new RemoteInputStreamSrvImpl(inputStream);
-
-          // prepare it for exporting
-          UnicastRemoteObject.exportObject(srv);
-
-          remoteInputStream = new RemoteInputStream(srv);
-
-          // modify the database
-          stmtCount =
-              this.getSession().setModel(remoteInputStream,
-                                         destinationURI, // model to redefine
-                                         new ModelResource(sourceURI));
-        }
-        catch (IOException ex) {
-          logger.error("Error attempting to load : " + sourceURI, ex);
-          throw new QueryException("Error attempting to load : " + sourceURI, ex);
-        } finally {
-          if ( srv != null ) {
-            try {
-              UnicastRemoteObject.unexportObject(srv, false);
-            } catch ( NoSuchObjectException ex ) {};
-          }
-        }
-      }
-      else {
-
-        if ( logger.isInfoEnabled() ) {
-          logger.info("loading remote resource : " + sourceURI );
-        }
-
-        // modify the database using a remote file located on the server
-        // default behaviour
-
-        stmtCount =
-            this.getSession().setModel(destinationURI, // model to redefine
-                                       new ModelResource(sourceURI));
-      }
-      update();
-
-      // log that we've loaded the contents of the file
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Loaded " + stmtCount + " statements from " + sourceURI +
-                     " into " + destinationURI);
-      }
-
-      // tell the user
-      if (stmtCount > 0L) {
-
-        this.setLastMessage("Successfully loaded " + stmtCount +
-                            " statements from " + sourceURI + " into " +
-                            destinationURI);
-      }
-      else {
-
-        this.setLastMessage("WARNING: No valid RDF statements found in " +
-                            sourceURI);
-      } // end if
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not load " + sourceURI + " into " +
-                          destinationURI + EOL + this.getCause(qe, 2));
-      logger.warn("Failed to load " + sourceURI + " into " + destinationURI,
-                  qe);
-    }
-    catch (RuntimeException re) {
-
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Failed to load statements:" + this.getCause(re, 0));
-      logger.fatal("Failed to load statements", re);
-    }
-    finally {
-
-      // close the inputstream in-case the server was not able to
-      // complete the task.
-      if ( remoteInputStream != null ) {
-        try {
-          remoteInputStream.close();
-        } catch ( Exception ex ) {};
-      }
-
-    }
-    // try-catch
-
-  }
-
-  // outALoadCommand()
-
-  /**
-   * Executes an iTQL script.
-   *
-   * @param node the execute command
-   */
-  public void outAExecuteCommand(AExecuteCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing execute command " + node);
-    }
-
-    // get the name of the script to execute
-    String resource = node.getResource().getText();
-
-    // keep a record of the line number
-    int line = 0;
-
-    try {
-
-      // convert the script to a URL
-      URL scriptURL = new URL(resource);
-
-      // log that we're executing a script
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Executing  script " + scriptURL);
-      }
-
-      // create a buffer to hold the results in
-      StringBuffer resultsMsg = new StringBuffer();
-
-      // create a reader to read the contents of the script
-      BufferedReader scriptIn =
-          new BufferedReader(new InputStreamReader(scriptURL.openStream()));
-
-      // execute the script!
-      String command = scriptIn.readLine();
-
-      while (command != null) {
-
-        // increment the line number
-        line++;
-
-        if (!command.equals("")) {
-
-          // execute the command
-          executeCommand(command);
-        }
-
-        // end if
-        // get the next command
-        command = scriptIn.readLine();
-      }
-
-      // end if
-      // tell the user
-      resultsMsg.append("Completed execution of script " + resource);
-      this.setLastMessage(resultsMsg.toString());
-    }
-    catch (ParserException pe) {
-
-      // let the user know the problem
-      this.setLastError(pe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Syntax error in script (line " + line + "): " +
-                          pe.getMessage());
-      logger.warn("Unable to execute script - " + resource + EOL +
-                  this.getCause(pe, 0));
-    }
-    catch (LexerException le) {
-
-      // let the user know the problem
-      this.setLastError(le);
-      this.setLastAnswer(null);
-      this.setLastMessage("Syntax error in script (line " + line + "): " +
-                          le.getMessage());
-      logger.warn("Unable to execute script - " + resource + EOL +
-                  this.getCause(le, 0));
-    }
-    catch (MalformedURLException mue) {
-
-      // let the user know the problem
-      this.setLastError(mue);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not execute script: Invalid script URL.");
-      logger.warn("Invalid script source URL." + EOL + this.getCause(mue, 0));
-    }
-    catch (Exception e) {
-
-      // let the user know the problem
-      this.setLastError(e);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not execute script." + EOL +
-                          this.getCause(e, 0));
-      logger.error("Unable to execute script - " + resource + EOL +
-                   this.getCause(e, 0));
-    }
-    // try-catch
-  }
-
-  // outAExecuteCommand()
-
-  /**
-   * Inserts a triple, model, database or the results of a query into a model or
-   * database.
-   *
-   * @param node the insert command
-   */
-  public void outAInsertCommand(AInsertCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing insert command " + node);
-    }
-
-    // get the resource we're inserting data into
-    URI resourceURI = toURI(node.getResource());
-
-    try {
-
-      // log that we're inserting the statments
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Inserting statements into " + resourceURI);
-      }
-
-      // update the session
-      this.updateSession(new ModelResource(resourceURI));
-
-      // insert the statements into the model
-      insertStatements(resourceURI, node.getTripleFactor());
-      update();
-
-      // log that we've inserted the statments
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Completed inserting statements into " + resourceURI);
-      }
-
-      // tell the user
-      this.setLastMessage(
-          "Successfully inserted statements into " + resourceURI
-          );
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not insert statements into " + resourceURI +
-                          EOL + this.getCause(qe, 2));
-      logger.warn("Failed to insert statements into " + resourceURI, qe);
-    }
-    catch (URISyntaxException use) {
-
-      // let the user know the problem
-      this.setLastError(use);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not insert into resource: Invalid resource " +
-                          "URI.");
-      logger.warn("Invalid resource URI." + EOL + this.getCause(use, 0));
-    }
-    catch (RuntimeException re) {
-
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Failed to insert statements:" + this.getCause(re, 0));
-      logger.fatal("Failed to insert statements", re);
-    }
-  }
-
-  // outAInsertCommand()
-
-  /**
-   * Deletes a triple, model, database or the results of a query from a model or
-   * database.
-   *
-   * @param node the delete command
-   */
-  public void outADeleteCommand(ADeleteCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing delete command " + node);
-    }
-
-    // get the resource we're deleting data from
-    URI resourceURI = toURI(node.getResource());
-
-    try {
-
-      // log that we're deleting the statments
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Deleting statements from " + resourceURI);
-      }
-
-      // update the session
-      this.updateSession(new ModelResource(resourceURI));
-
-      // delete the statements from the model
-      deleteStatements(resourceURI, node.getTripleFactor());
-      update();
-
-      // log that we've inserted the statments
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Completed deleting statements from " + resourceURI);
-      }
-
-      // tell the user
-      this.setLastMessage(
-          "Successfully deleted statements from " + resourceURI
-          );
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not delete statements from " + resourceURI +
-                          EOL + this.getCause(qe, 2));
-      logger.warn("Failed to delete statements from " + resourceURI, qe);
-    }
-    catch (URISyntaxException use) {
-
-      // let the user know the problem
-      this.setLastError(use);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not delete from resource: Invalid resource " +
-                          "URI.");
-      logger.warn("Invalid resource URI." + EOL + this.getCause(use, 0));
-    }
-    catch (RuntimeException re) {
-
-      // let the user know the problem
-      this.setLastError(re);
-      this.setLastAnswer(null);
-      this.setLastMessage("Failed to delete statements:" + this.getCause(re, 0));
-      logger.fatal("Failed to delete statements", re);
-    }
-
-    // try-catch
-  }
-
-  // outADeleteCommand()
-
-  /**
-   * Sets an interpreter property.
-   *
-   * @param node the set command
-   */
-  public void outASetCommand(ASetCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing set command " + node);
-    }
-
-    // get the option to set
-    PSetOption option = node.getSetOption();
-
-    // log that we've got the option
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Found option " + option);
-    }
-
-    // get the value
-    PSetOptionMode optionMode = node.getSetOptionMode();
-    boolean optionSet = false;
-
-    if (optionMode instanceof AOffSetOptionMode) {
-
-      optionSet = false;
-    }
-    else {
-
-      optionSet = true;
-    } // end if
-
-    // set the option
-    if (option instanceof ATimeSetOption) {
-
-      // set the time option
-      this.setTimeOption(optionSet);
-
-      // return the user a message
-      this.setLastMessage("Command timing is " + (optionSet ? "on" : "off"));
-    }
-    else if (option instanceof AAutocommitSetOption) {
-
-      /* Do not assume this.  As the server may have
-         encountered an error.
-      if (optionSet == autoCommit) {
-        if (logger.isDebugEnabled()) {
-          logger.debug("Autocommit option is already " + autoCommit);
-        } // end if
-        return;
-      }
-      */
-
-      try {
-
-        // log that we got a autocommit option
-        if (logger.isDebugEnabled()) {
-
-          logger.debug("Found autocommit option, setting to " +
-                       (optionSet ? "on" : "off"));
-        } // end if
-
-        // set the auto commit status
-        if (session != null) {
-          this.getSession().setAutoCommit(optionSet);
-          // set the state of a transaction to clean, only if we have just finished a transaction
-          if (!autoCommit && optionSet) {
-            autoCommit = optionSet;
-            update();
-          }
-        }
-        autoCommit = optionSet;
-
-        if (logger.isDebugEnabled()) {
-          logger.debug("Set autocommit to " + (optionSet ? "on" : "off"));
-        }
-
-        // return the user a message
-        this.setLastMessage("Auto commit is " + (optionSet ? "on" : "off"));
-      }
-      catch (QueryException qe) {
-
-        // let the user know the problem
-        this.setLastError(qe);
-        this.setLastAnswer(null);
-        this.setLastMessage("Unable to set interpreter option" + EOL +
-                            this.getCause(qe, 2));
-        logger.warn("Unable to set interpreter property", qe);
-      }
-
-      // try-catch
-    }
-    else {
-
-      // this should never get through the parser, if it does it probably
-      // means the grammar has been updated
-      this.setLastMessage("Unknown interpreter option");
-    }
-
-    // end if
-    // log the option setting
-    if (logger.isDebugEnabled()) {
-
-      logger.debug(option + "has been set to " + optionSet);
-    }
-  }
-
-  // outASetCommand()
-
-  /**
-   * Backs up the contents of a server to a local or remote file.
-   *
-   * @param node the backup command
-   */
-  public void outABackupCommand(ABackupCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    RemoteOutputStream outputStream = null;
-    RemoteOutputStreamSrvImpl srv = null;
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing backup command " + node);
-    }
-
-    // get the server we'll be backing up
-    URI sourceURI = toURI(node.getSource());
-
-    // get the resource we're writing to
-    URI destinationURI = toURI(node.getDestination());
-
-    try {
-
-      // set the server uri given a possible model
-      this.setBackupServer(sourceURI);
-
-      // are we backing up a file locally to the client?
-      if ( node.getLocality() != null &&
-           (node.getLocality() instanceof ALocalLocality) ) {
-
-        if ( logger.isInfoEnabled() ) {
-          logger.info("backing up local resource : " + sourceURI );
-        }
-
-        try {
-
-          // open and wrap the outputstream
-          srv = new RemoteOutputStreamSrvImpl(
-                  new FileOutputStream(destinationURI.getPath()));
-
-          // prepare it for exporting
-          UnicastRemoteObject.exportObject(srv);
-
-          outputStream = new RemoteOutputStream(srv);
-
-        }
-        catch (IOException ex) {
-          logger.error("Error attempting to backing up : " + sourceURI, ex);
-        }
-
-        try {
-
-          // back it up to the local file system
-          this.getSession().backup(sourceURI, outputStream);
-
-        } finally {
-
-          // ensure the stream is closed in case the server was not able
-          // to close it.
-          if ( outputStream != null ) {
-            try {
-              outputStream.close();
-            } catch ( IOException ioex ) {};
-            if ( srv != null ) {
-              try {
-                UnicastRemoteObject.unexportObject(srv, false);
-              } catch ( NoSuchObjectException ex ) {};
-            }
-          }
-        }
-
-      }
-      else {
-
-        // back it up via the server
-        this.getSession().backup(sourceURI, destinationURI);
-      }
-
-      // log that we've inserted the statments
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Completed backing up " + sourceURI +
-                     " to " + destinationURI);
-      }
-
-      // tell the user
-      this.setLastMessage("Successfully backed up " + sourceURI +
-                          " to " + destinationURI + ".");
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not backup " + sourceURI + " to " +
-                          destinationURI + EOL + this.getCause(qe, 2) + ".");
-      logger.warn("Failed to backup server " + sourceURI + " to " +
-                  destinationURI,
-                  qe);
-    }
-
-    // try-catch
-  }
-
-  // outABackupCommand()
-
-  /**
-   * Restores the contents of a server from a file.
-   *
-   * @param node the restore command
-   */
-  public void outARestoreCommand(ARestoreCommand node) {
-
-    this.setLastError(null);
-    this.setLastAnswer(null);
-    this.setLastMessage("");
-
-    RemoteInputStream inputStream = null;
-    RemoteInputStreamSrvImpl srv = null;
-
-    // log the command
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Processing restore command " + node);
-    }
-
-    // get the server we'll be restoring to
-    URI destinationURI = toURI(node.getDestination());
-
-    // get the resource we're reading from
-    URI sourceURI = toURI(node.getSource());
-
-    try {
-
-      // log that we're backing up a server
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Restoring server " + destinationURI + " from " +
-                     sourceURI);
-      }
-
-      setServerURI(destinationURI);
-
-      // are we loading the file locally from the client?
-      if ( node.getLocality() != null &&
-           (node.getLocality() instanceof ALocalLocality) ) {
-
-        if ( logger.isInfoEnabled() ) {
-          logger.info("restoring local resource : " + sourceURI );
-        }
-
-        try {
-
-          // open and wrap the inputstream
-          srv = new RemoteInputStreamSrvImpl(sourceURI.toURL().openStream());
-
-          // prepare it for exporting
-          UnicastRemoteObject.exportObject(srv);
-
-          inputStream = new RemoteInputStream(srv);
-
-          // modify the database
-          this.getSession().restore( inputStream, destinationURI, sourceURI);
-        }
-        catch (IOException ex) {
-          logger.error("Error attempting to restore : " + sourceURI, ex);
-          throw new QueryException("Error attempting to restore : " + sourceURI, ex);
-        }
-        finally {
-          if ( srv != null ) {
-            try {
-              UnicastRemoteObject.unexportObject(srv, false);
-            } catch ( NoSuchObjectException ex ) {};
-          }
-        }
-      }
-      else {
-
-        // restore it from the server
-        this.getSession().restore(destinationURI, sourceURI);
-
-      }
-
-      update();
-
-      // log that we've inserted the statments
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Completed restoring " + destinationURI + " from " +
-                     sourceURI);
-      }
-
-      // tell the user
-      this.setLastMessage("Successfully restored " + destinationURI + " from " +
-                          sourceURI);
-    }
-    catch (QueryException qe) {
-
-      // let the user know the problem
-      this.setLastError(qe);
-      this.setLastAnswer(null);
-      this.setLastMessage("Could not restore " + destinationURI + " from " +
-                          sourceURI + EOL + this.getCause(qe, 2));
-      logger.warn("Failed to restore server " + destinationURI + " from " +
-                  sourceURI, qe);
-    }
-    finally {
-
-      // close the inputstream in-case the server was not able to
-      // complete the task.
-      if ( inputStream != null ) {
-        try {
-         inputStream.close();
-        }
-        catch ( Exception ex ) {};
-      }
-    }
-  }
-
-  /**
-   * Sets the error of the last query. Methods overriding <code>DepthFirstAdapter</code>
-   * are expected to set a result for successful queries, and <code>null</code>
-   * for failed ones.
-   *
-   * @param lastError the exception of the last command execution
-   */
-  void setLastError(Exception lastError) {
-
-    // carefully set the answer by value rather than reference
-    this.lastError =
-        (lastError == null) ? null : new ItqlInterpreterException(lastError);
-  }
-
-  /**
-   * Sets the results of the last command execution. Methods overriding <code>DepthFirstAdapter</code>
-   * are expected to set a results message, even if that message is null.
-   *
-   * @param lastMessage the results of the last command execution
-   */
-  void setLastMessage(String lastMessage) {
-
-    this.lastMessage = lastMessage;
-  }
-
-  // setLastMessage()
-
-  /**
-   * Returns the driver used to communicate with the database.
-   *
-   * @return the driver used to communicate with the database
-   */
-  Session getSession() throws QueryException {
-
-    if (providedSession != null) {
-      if (session != providedSession) {
-        session = providedSession;
-      }
-    }
-
-    if (this.session == null) {
-      throw new QueryException("Null session");
-    }
-    return this.session;
-  }
-
-  // getCause()
-
-  /**
-   * Sets the option to enable the timing of commands.
-   *
-   * @param timeOption the option to enable the timing of commands
-   */
-  private void setTimeOption(boolean timeOption) {
-
-    this.timeOption = timeOption;
-  }
-
-  // getTimeOption()
-
-  /**
-   * Sets the time a command started.
-   *
-   * @param commandStartTime the time a command started
-   */
-  private void setCommandStartTime(long commandStartTime) {
-
-    this.commandStartTime = commandStartTime;
-  }
-
-  // getCommandStartTime()
-
-  /**
-   * Sets the driver used to communicate with the database.
-   *
-   * @param session  the driver used to communicate with the database
-   * @param securityDomainURI  the security domain of the <var>session</var>
-   * @throws QueryException if the state of the original session couldn't be
-   *   propagated to the new <var>session</var>.
-   */
-  void setSession(Session session, URI securityDomainURI) throws QueryException {
-    // override all sessions with the provided one.
-    if (providedSession != null) {
-      session = providedSession;
-      return;
-    }
-
-    if (logger.isDebugEnabled()) {
-      logger.debug(
-          "Setting session to " + session + ", security domain " +
-          securityDomainURI
-          );
-    }
-
-    // Short-circuit reassignment of the same session
-    if (this.session == session) {
-      if (logger.isDebugEnabled()) {
-        logger.debug("Didn't need to set session");
-      }
-      return;
-    }
-
-    // We can't change sessions if we're in the midst of a transaction which
-    // has already updated the server
-    if (transactionUpdated) {
-      throw new QueryException(
-          "Can't access more than one server in a transaction"
-          );
-    }
-
-    // Propagate the autoCommit property to the new session
-    if (!autoCommit) {
-      if (logger.isDebugEnabled()) {
-        logger.debug("Setting autocommit to " + autoCommit + " on " + serverURI);
-      }
-      if (session != null) {
-        session.setAutoCommit(autoCommit);
-      }
-      if (this.session != null) {
-        this.session.setAutoCommit(true); // TODO: this requires a compensating
-        //       transaction in case of
-        //       failure
-      }
-    }
-
-    // Propagate the login to the new session
-    Login login = (Login) loginMap.get(securityDomainURI);
-    if (login != null) {
-      if (logger.isDebugEnabled()) {
-        logger.debug("Logging " + login.username + " into " + serverURI);
-      }
-      session.login(securityDomainURI, login.username, login.password);
-    }
-    else {
-      if (logger.isDebugEnabled()) {
-        logger.debug("No credentials to propagate for " + securityDomainURI);
-      }
-    }
-
-    if (this.session != null) {
-      // Close existing session
-      if (logger.isDebugEnabled()) {
-        logger.debug("Closing session");
-      }
-
-      try {
-        this.session.close();
-      }
-      catch (QueryException e) {
-        logger.warn("Couldn't close session (abandoning)", e);
-      }
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Closed session");
-      }
-    }
-
-    // Reassign session
-    if (session != null) {
-      isLocal = session.isLocal();
-    }
-    this.session = session;
-    this.securityDomainURI = securityDomainURI;
-  }
-
-  // getSession()
-
-  /**
-   * Sets the alias map associated with this session.
-   *
-   * @param aliasMap the alias map associated with this session
-   */
-  void setAliasMap(Map aliasMap) {
-
-    this.aliasMap = aliasMap;
-  }
-
-  // addAliasPair()
-
-  /**
-   * Sets the flag indicating whether the user has entered the quit command
-   *
-   * @param quitRequested The new QuitRequested value
-   */
-  private void setQuitRequested(boolean quitRequested) {
-
-    this.quitRequested = quitRequested;
-  }
-
-  // setQuitRequested()
-
-  /**
-   * Sets the results of the last query. Methods overriding <code>DepthFirstAdapter</code>
-   * are expected to set a result for successful queries, and <code>null</code>
-   * for failed ones.
-   *
-   * @param lastAnswer the results of the last command execution
-   */
-  private void setLastAnswer(Answer lastAnswer) {
-
-    this.lastAnswer = lastAnswer;
-  }
-
-  /**
-   * Insert a set of triples.  Calls the server if it can be done only on the
-   * server.
-   *
-   * @param tripleFactor a triple, model or query from the parser
-   * @throws QueryException if <code>tripleFactor</code> contains a query that
-   *      cannot be executed, or after evaluation contains no statements
-   * @throws URISyntaxException if <code>tripleFactor</code> contains a query or
-   *      a resource that that violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC\uFFFD2396</a>
-   */
-  private void insertStatements(URI modelURI, PTripleFactor tripleFactor) throws
-      QueryException, URISyntaxException {
-
-    // validate tripleFactor parameter
-    if (tripleFactor == null) {
-
-      throw new IllegalArgumentException("Null \"tripleFactor\" parameter");
-    }
-
-    // log that we're finding statements
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Finding statements in expression " + tripleFactor);
-    }
-
-    // get the set of triples out of the factor
-    PSetOfTriples setOfTriples = null;
-
-    if (tripleFactor instanceof ABracedTripleFactor) {
-
-      setOfTriples = ( (ABracedTripleFactor) tripleFactor).getSetOfTriples();
-    }
-    else if (tripleFactor instanceof AUnbracedTripleFactor) {
-
-      setOfTriples = ( (AUnbracedTripleFactor) tripleFactor).getSetOfTriples();
-    }
-
-    // drill down into the set of triples
-    if (setOfTriples instanceof AResourceSetOfTriples) {
-
-      // log that we've found a resource
-      if (logger.isDebugEnabled()) {
-
-        URI resourceURI =
-            toURI( ( (AResourceSetOfTriples) setOfTriples).getResource());
-        logger.debug("Found resource " + resourceURI + "in triple factor");
-      }
-
-      // TODO: implement this once we can select all triples from a model
-      // we cannot currently handle inserting or deleting a complete model
-      // into/from another
-      throw new UnsupportedOperationException("Models cannot be inserted " +
-                                              "into or deleted from other models");
-    }
-    else if (setOfTriples instanceof ASelectSetOfTriples) {
-
-      // build the query
-      Query query = this.buildQuery( ( (ASelectSetOfTriples) setOfTriples));
-
-      // log that we've created the query and will execute it
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Executing query " + query);
-      }
-
-      getSession().insert(modelURI, query);
-    }
-    else if (setOfTriples instanceof ATripleSetOfTriples) {
-
-      Map variableMap = new HashMap();
-      Set statements = getStatements( (ATripleSetOfTriples) setOfTriples,
-          variableMap);
-      getSession().insert(modelURI, statements);
-    }
-  }
-
-  /**
-   * Delete a set of triples.  Calls the server if it can be done only on the
-   * server.
-   *
-   * @param tripleFactor a triple, model or query from the parser
-   * @throws QueryException if <code>tripleFactor</code> contains a query that
-   *      cannot be executed, or after evaluation contains no statements
-   * @throws URISyntaxException if <code>tripleFactor</code> contains a query or
-   *      a resource that that violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC\uFFFD2396</a>
-   */
-  private void deleteStatements(URI modelURI, PTripleFactor tripleFactor) throws
-      QueryException, URISyntaxException {
-
-    // validate tripleFactor parameter
-    if (tripleFactor == null) {
-
-      throw new IllegalArgumentException("Null \"tripleFactor\" parameter");
-    }
-
-    // log that we're finding statements
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Finding statements in expression " + tripleFactor);
-    }
-
-    // get the set of triples out of the factor
-    PSetOfTriples setOfTriples = null;
-
-    if (tripleFactor instanceof ABracedTripleFactor) {
-
-      setOfTriples = ( (ABracedTripleFactor) tripleFactor).getSetOfTriples();
-    }
-    else if (tripleFactor instanceof AUnbracedTripleFactor) {
-
-      setOfTriples = ( (AUnbracedTripleFactor) tripleFactor).getSetOfTriples();
-    }
-
-    // drill down into the set of triples
-    if (setOfTriples instanceof AResourceSetOfTriples) {
-
-      // log that we've found a resource
-      if (logger.isDebugEnabled()) {
-
-        URI resourceURI =
-            toURI( ( (AResourceSetOfTriples) setOfTriples).getResource());
-        logger.debug("Found resource " + resourceURI + "in triple factor");
-      }
-
-      // TODO: implement this once we can select all triples from a model
-      // we cannot currently handle inserting or deleting a complete model
-      // into/from another
-      throw new UnsupportedOperationException("Models cannot be inserted " +
-                                              "into or deleted from other models");
-    }
-    else if (setOfTriples instanceof ASelectSetOfTriples) {
-
-      // build the query
-      Query query = this.buildQuery( ( (ASelectSetOfTriples) setOfTriples));
-
-      // log that we've created the query and will execute it
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Executing query " + query);
-      }
-
-      getSession().delete(modelURI, query);
-    }
-    else if (setOfTriples instanceof ATripleSetOfTriples) {
-
-      Map variableMap = new HashMap();
-      Set statements = getStatements((ATripleSetOfTriples) setOfTriples,
-          variableMap);
-      if (variableMap.size() > 0) {
-        throw new QueryException("Cannot use variables when deleting " +
-            "statements");
-      }
-      getSession().delete(modelURI, statements);
-    }
-  }
-
-  /**
-   * Returns a set of statements from the iTQL query object.
-   *
-   * @param setOfTriples the set of statements defined in the query.
-   * @param variableMap the variable map to store the value of the variable
-   *   against the variable object.
-   * @throws URISyntaxException if <code>tripleFactor</code> contains a query or
-   *      a resource that that violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC\uFFFD2396</a>
-   * @throws QueryException if an invalid node is used in the set of triples.
-   * @return a set of statements from the iTQL query.
-   */
-  public Set getStatements(ATripleSetOfTriples setOfTriples, Map variableMap)
-      throws QueryException, URISyntaxException {
-
-    List tripleList = setOfTriples.getTriple();
-    HashSet statements = new HashSet();
-
-    // Check that each set of triples has the predicate bound.
-    for (Iterator i = tripleList.iterator(); i.hasNext(); ) {
-
-      // get the triple
-      ATriple triple = (ATriple) i.next();
-
-      // Convert the Subject, Predicate and Object.
-      org.jrdf.graph.Node subject = toNode(triple.getSubject(), variableMap);
-      org.jrdf.graph.Node predicate = toNode(triple.getPredicate(), variableMap);
-      org.jrdf.graph.Node object = toNode(triple.getObject(), variableMap);
-
-      // Predicate cannot be a blank node.
-      if (predicate instanceof BlankNode) {
-        throw new QueryException("Predicate must be a valid URI");
-      }
-
-      // Check that the subject or predicate node is not a literal.
-      if (subject instanceof LiteralImpl ||
-          predicate instanceof LiteralImpl) {
-
-        // throw an exception indicating we have a bad triple
-        throw new QueryException(
-            "Subject or Predicate cannot be a literal");
-      }
-
-      // Create a new statement using the triple elements
-      org.jrdf.graph.Triple jrdfTriple = new TripleImpl(
-          (SubjectNode) subject, (PredicateNode) predicate,
-          (ObjectNode) object);
-
-      // add the statement to the statement set
-      statements.add(jrdfTriple);
-    }
-
-    return statements;
-  }
-
-  /**
-   * Builds a set of {@link org.jrdf.graph.Triple}s from a
-   * {@link org.mulgara.query.Answer}.
-   *
-   * @param answer the results of a query
-   * @return a set of {@link org.jrdf.graph.Triple}s, suitable for use in
-   *      inserting or deleting data to or from a model
-   * @throws QueryException EXCEPTION TO DO
-   */
-  private Set getStatements(Answer answer) throws QueryException {
-
-    // validate answer parameter
-    if (answer == null) {
-
-      throw new IllegalArgumentException("Null \"answer\" parameter");
-    } // end if
-
-    // log that we're parsing an answer into a set of statements
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Parsing answer into set of statements");
-    }
-
-    try {
-      Set statements = new HashSet();
-      answer.beforeFirst();
-
-      while (answer.next()) {
-
-        if (! (answer.getObject(0) instanceof ObjectNode)) {
-
-          throw new QueryException("Subject is not a resource for [" +
-                                   answer.getObject(0) + " " +
-                                   answer.getObject(1) +
-                                   " " +
-                                   answer.getObject(2) + "]");
-        }
-
-        if (! (answer.getObject(1) instanceof URIReference)) {
-
-          throw new QueryException("Predicate is not a resource for [" +
-                                   answer.getObject(0) + " " +
-                                   answer.getObject(1) +
-                                   " " +
-                                   answer.getObject(2) + "]");
-        }
-
-        statements.add(new TripleImpl( (SubjectNode) answer.getObject(0),
-                                      (PredicateNode) answer.getObject(1),
-                                      (ObjectNode) answer.getObject(2)));
-      }
-
-      logger.debug("Parsed answer into " + statements.size());
-
-      return statements;
-    }
-    catch (TuplesException e) {
-      throw new QueryException("Couldn't parse answer into statements", e);
-    }
-  } // setStatements
-
-  /**
-   * Returns the option to enable the timing of commands.
-   *
-   * @return the option to enable the timing of commands
-   */
-  private boolean getTimeOption() {
-
-    return timeOption;
-  }
-
-  /**
-   * Return the time a command started.
-   *
-   * @return the time a command started
-   */
-  private long getCommandStartTime() {
-
-    return commandStartTime;
-  }
-
-  /**
-   * Returns the alias map associated with this session.
-   *
-   * @return the alias namespace map associated with this session
-   */
-  Map getAliasMap() {
-
-    return this.aliasMap;
-  }
-
-  //
-  // Internal methods
-  //
-
-  /**
-   * Executes a query and returns its results.
-   *
-   * @param rawQuery a select query, represented as either a {@link
-   *      org.mulgara.itql.node.ASelectCommand} or a {@link
-   *      org.mulgara.itql.node.ASelectSetOfTriples}
-   * @return the answer to the query
-   * @throws QueryException if the query cannot be executed
-   * @throws URISyntaxException if the <code>query</code> contains a resource
-   *      whose text violates <a href="http://www.isi.edu/in-notes/rfc2396.txt">
-   *      RFC\uFFFD2396</a>
-   */
-  public Query buildQuery(org.mulgara.itql.node.Node rawQuery) throws
-      QueryException, URISyntaxException {
-
-    // validate query parameter
-    if (rawQuery == null) {
-
-      throw new IllegalArgumentException("Null \"rawQuery\" parameter");
-    }
-
-    // end if
-    // create the variables needed...
-    LinkedList variables = null;
-    AFromClause fromClause;
-    AWhereClause whereClause;
-    AOrderClause orderClause;
-    AHavingClause havingClause;
-    ALimitClause limitClause;
-    AOffsetClause offsetClause;
-
-    // cast the correct way (we don't have a common superclass, event though we
-    // have methods with the same names)
-    if (rawQuery instanceof AQuery) {
-
-      AQuery query = (AQuery) rawQuery;
-      PSelectClause selectClause = query.getSelectClause();
-      if (selectClause instanceof ANormalSelectSelectClause) {
-        variables = ( (ANormalSelectSelectClause) selectClause).getElement();
-      }
-      fromClause = ( (AFromClause) query.getFromClause());
-      whereClause = ( (AWhereClause) query.getWhereClause());
-      orderClause = ( (AOrderClause) query.getOrderClause());
-      havingClause = ( (AHavingClause) query.getHavingClause());
-      limitClause = ( (ALimitClause) query.getLimitClause());
-      offsetClause = ( (AOffsetClause) query.getOffsetClause());
-    }
-    else if (rawQuery instanceof ASelectSetOfTriples) {
-
-      ASelectSetOfTriples query = (ASelectSetOfTriples) rawQuery;
-      variables = new LinkedList();
-      variables.add(query.getSubject());
-      variables.add(query.getPredicate());
-      variables.add(query.getObject());
-      fromClause = ( (AFromClause) query.getFromClause());
-      whereClause = ( (AWhereClause) query.getWhereClause());
-      orderClause = ( (AOrderClause) query.getOrderClause());
-      havingClause = ( (AHavingClause) query.getHavingClause());
-      limitClause = ( (ALimitClause) query.getLimitClause());
-      offsetClause = ( (AOffsetClause) query.getOffsetClause());
-    }
-    else {
-
-      // we only handle AQuery and ASelectSetOfTriples
-      throw new IllegalArgumentException("Invalid type for \"rawQuery\" " +
-                                         "parameter");
-    }
-
-    if (fromClause == null) {
-
-      throw new QueryException("FROM clause missing.");
-    }
-
-    if (whereClause == null) {
-
-      throw new QueryException("WHERE clause missing.");
-    }
-
-    // end if
-    // log that we're about to build the variable list
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building query variable list from " + variables);
-    }
-
-    // build the variable list
-    List variableList = this.buildVariableList(variables);
-
-    // log that we've built the variable list
-    if (logger.isDebugEnabled()) {
-      logger.debug("Built variable list " + variableList);
-    }
-
-    // get the model expression from the parser
-    PModelExpression rawModelExpression = fromClause.getModelExpression();
-
-    // log that we're about to build the model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building model expression from " + rawModelExpression);
-    }
-
-    // parse the text into a model expression
-    ModelExpression modelExpression =
-        ModelExpressionBuilder.build(this.getAliasMap(), rawModelExpression);
-
-    // log that we've built the model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Built model expression " + modelExpression);
-    }
-
-    // get the constraint expression from the parser
-    PConstraintExpression rawConstraintExpression =
-        whereClause.getConstraintExpression();
-
-    // log that we're about to build the constraint expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building constraint expression from " +
-                   rawConstraintExpression);
-    }
-
-    // parse the text into a constraint expression
-    ConstraintExpression constraintExpression = build(rawConstraintExpression);
-
-    // log that we've build the constraint expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Built constraint expression " + constraintExpression);
-    }
-
-    // build the order list
-    List orderList = Collections.EMPTY_LIST;
-
-    if (orderClause != null) {
-
-      orderList = buildOrderList(orderClause.getOrderElement());
-    }
-
-    // build the having clause
-    ConstraintHaving havingExpression = null;
-
-    if (havingClause != null) {
-      // get the constraint expression from the parser
-      PConstraintExpression rawHavingExpression =
-          havingClause.getConstraintExpression();
-
-      // log that we're about to build the constraint expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Building constraint expression from " +
-                     rawHavingExpression);
-      }
-
-      // parse the text into a constraint expression
-      havingExpression = buildHaving(rawHavingExpression);
-    }
-
-    // build the limit
-    Integer limit = null;
-
-    if (limitClause != null) {
-
-      try {
-
-        limit = new Integer(limitClause.getNumber().getText());
-      }
-      catch (NumberFormatException e) {
-
-        throw new Error("Sable parser permitted non-integer limit", e);
-      }
-    }
-
-    // build the offset
-    int offset = 0;
-
-    if (offsetClause != null) {
-
-      try {
-
-        offset = Integer.parseInt(offsetClause.getNumber().getText());
-      }
-      catch (NumberFormatException e) {
-
-        throw new Error("Sable parser permitted non-integer offset", e);
-      }
-    }
-
-    // build a query using the information we've obtained from the parser
-    // (all answers are acceptable)
-    lastQuery = new Query(variableList, modelExpression, constraintExpression,
-        havingExpression, orderList, limit, offset, new UnconstrainedAnswer());
-
-    return lastQuery;
-  }
-
-  /**
-   * Builds a list of {@link org.mulgara.query.Variable}s from a list of
-   * {@link org.mulgara.itql.node.PVariable}s. Note. Variables in both the
-   * <code>rawVariableList</code> and the returned list will <strong>not
-   * </strong> contain the variable prefix <code>$</code> in their name.
-   *
-   * @param rawVariableList a list of {@link
-   *      org.mulgara.itql.node.PVariable}s from the parser
-   * @return a list of {@link org.mulgara.query.Variable}s, suitable for use
-   *      in creating a {@link org.mulgara.query.Query}
-   * @throws QueryException if the <code>rawVariableList</code> cannot be parsed
-   *      into a list of {@link org.mulgara.query.Variable}s
-   */
-  private List buildVariableList(LinkedList rawVariableList) throws
-      QueryException, URISyntaxException {
-
-    // Empty variable list.
-    if (rawVariableList == null) {
-      return Collections.EMPTY_LIST;
-    }
-
-    // validate rawVariableList parameter
-    if (rawVariableList.size() == 0) {
-      throw new IllegalArgumentException("Empty \"rawVariableList\" parameter");
-    }
-
-    // Construct the required builder
-    VariableBuilder variableBuilder = new VariableBuilder(this,
-        variableFactory);
-
-    // end if
-    // log that we're building the variable list
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building variable list from " + rawVariableList);
-    }
-
-    // copy each variable from the query into the list
-    for (Iterator i = rawVariableList.iterator(); i.hasNext(); ) {
-      PElement element = (PElement) i.next();
-      element.apply( (Switch) variableBuilder);
-    }
-
-    // Get the variable list
-    List variableList = variableBuilder.getVariableList();
-
-    // make sure that we return a list with something in it
-    if (variableList.size() == 0) {
-      throw new QueryException("No variables parseable from query");
-    }
-
-    // log that we've successfully built the variable list
-    if (logger.isDebugEnabled()) {
-      logger.debug("Built variable list " + variableList);
-    }
-
-    // return the list
-    return variableList;
-  }
-
-  /**
-   * Builds a list of {@link org.mulgara.query.Variable}s from a list of
-   * {@link org.mulgara.itql.node.POrderElement}s. Note. Variables in both
-   * the <code>rawVariableList</code> and the returned list will <strong>not
-   * </strong> contain the variable prefix <code>$</code> in their name.
-   *
-   * @param rawOrderList PARAMETER TO DO
-   * @return a list of {@link org.mulgara.query.Variable}s, suitable for use
-   *      in creating a {@link org.mulgara.query.Query}
-   * @throws QueryException if the <code>rawOrderElementList</code> cannot be
-   *      parsed into a list of {@link org.mulgara.query.Variable}s
-   */
-  private List buildOrderList(LinkedList rawOrderList) throws QueryException {
-
-    // validate rawOrderElementList parameter
-    if ( (rawOrderList == null) || (rawOrderList.size() == 0)) {
-
-      throw new IllegalArgumentException("Null \"rawOrderList\" parameter");
-    }
-
-    // end if
-    // log that we're building the variable list
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building order list from " + rawOrderList);
-    }
-
-    // create a list for the parsed variables
-    List orderList = new ArrayList(rawOrderList.size());
-
-    // copy each variable from the query into the list
-    for (Iterator i = rawOrderList.iterator(); i.hasNext(); ) {
-
-      AOrderElement order = (AOrderElement) i.next();
-
-      // get the name of this variable
-      String variableName =
-          ( (AVariable) order.getVariable()).getIdentifier().getText();
-
-      // log that we've found a variable
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found variable $" + variableName);
-      }
-
-      // Figure out which way to order, ascending or descending
-      boolean ascending;
-      PDirection direction = order.getDirection();
-
-      if (direction == null) {
-        ascending = true;
-      }
-      else if (direction instanceof AAscendingDirection) {
-        ascending = true;
-      }
-      else if (direction instanceof ADescendingDirection) {
-        ascending = false;
-      }
-      else {
-        throw new Error("Unknown direction field in order");
-      }
-
-      // add a new variable to the list
-      orderList.add(new Order(new Variable(variableName), ascending));
-    }
-
-    // end for
-    // make sure that we return a list with something in it
-    if (orderList.size() == 0) {
-
-      throw new QueryException("No variables parseable from query");
-    }
-
-    // log that we've successfully built the order list
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Built order list " + orderList);
-    }
-
-    // return the list
-    return orderList;
-  }
-
-  // getStatements()
-
-  /**
-   * Construct a {@link LiteralImpl} from a {@link PLiteral}.
-   *
-   * @param p  the instance to convert
-   */
-  public LiteralImpl toLiteralImpl(PLiteral p) {
-
-    ALiteral aLiteral = (ALiteral) p;
-
-    // Determine the datatype URI, if present
-    URI datatypeURI = null;
-    if (aLiteral.getDatatype() != null) {
-      datatypeURI = toURI( ( (ADatatype) aLiteral.getDatatype()).getResource());
-    }
-
-    // Determine the language code
-    String language = (datatypeURI == null) ? "" : null;
-
-    if (datatypeURI == null) {
-      return new LiteralImpl(getLiteralText(aLiteral), language);
-    }
-    else {
-      return new LiteralImpl(getLiteralText(aLiteral), datatypeURI);
-    }
-  }
-
-  /**
-   * Constructs a {@link org.jrdf.graph.Node} from a {@link
-   * org.mulgara.itql.node.PTripleElement}.
-   *
-   * @param element dd
-   * @param variableMap a {@link Map} of variable names (as string) to
-   *   {@link VariableNodeImpl} that are used to contain all variables.
-   * @return dd
-   * @throws QueryException if <code>element</code> is a {@link
-   *   org.mulgara.itql.node.AResourceTripleElement} whose text contains a
-   *   <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">qualified
-   *   name</a> with a prefix not defined in the <code>aliasMap</code>
-   * @throws URISyntaxException if <code>element</code> is a {@link
-   *   org.mulgara.itql.node.AResourceTripleElement} whose text doesn't
-   *   conform to <a href="http://www.isi.edu/in-notes/rfc2396.txt">
-   *   RFC\uFFFD2396</a>
-   */
-  private org.jrdf.graph.Node toNode(PTripleElement element, Map variableMap) throws
-      QueryException, URISyntaxException {
-
-    // validate the element parameter
-    if (element == null) {
-
-      throw new IllegalArgumentException("Null \"element\" parameter");
-    }
-
-    // end if
-    // log what we're doing
-    if (logger.isDebugEnabled()) {
-
-      logger.debug("Resolving " + element + "to a RDF node");
-    }
-
-    // create the node
-    org.jrdf.graph.Node node = null;
-
-    // get the node
-    if (element instanceof ALiteralTripleElement) {
-
-      // create a new literal with the given text
-      node = toLiteralImpl( ( (ALiteralTripleElement) element).getLiteral());
-    }
-    else if (element instanceof AResourceTripleElement) {
-
-      // create a new resource
-      node = new URIReferenceImpl(toURI(
-          ( (AResourceTripleElement) element).getResource()
-          ));
-    }
-    else if (element instanceof AVariableTripleElement) {
-
-      // get the variable
-      String variableName =
-          ( (AVariable) ( (AVariableTripleElement) element).getVariable()).
-          getIdentifier().getText();
-
-      // log what we're doing
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Resolved " + element + " to variable " + variableName);
-      }
-
-      if (variableMap.containsKey(variableName)) {
-
-        node = (VariableNodeImpl) variableMap.get(variableName);
-      }
-      else {
-
-        VariableNodeImpl variable = new VariableNodeImpl(variableName);
-        variableMap.put(variableName, variable);
-        node = variable;
-      }
-    } // end if
-
-    // return the node
-    return node;
-  }
-
-  /**
-   * Convert SableCC-generated {@link TResource} tokens into {@link URI}s.
-   *
-   * Resolution will treat the token as an XML
-   * <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">qualified
-   * names</a> if the {@link #aliasMap} <code>aliasMap</code> contains a key
-   * for the URI scheme part that can be treated as an XML namespace prefix.
-   * For example, <kbd>dc:title</kbd> is treated as a qname and mapped to the
-   * to the URI <kbd>http://purl.org/dc/elements/1.1/title</kbd>, assuming the
-   * {@link #aliasMap} had an entry mapping <code>"dc"</code> to the Dublin
-   * Core namespace.
-   *
-   * @param token  the token to be converted, which should actually be a
-   *   {@link TResource}
-   * @throws Error if the <var>token</var> text isn't syntactically
-   *   a {@link URI}; this shouldn't ever occur, assuming the <var>token</var>
-   *   is a {@link TResource}
-   */
-  public URI toURI(Token token) {
-
-    assert token instanceof TResource;
-
-    try {
-      // get the URI of the resource -- this may actually be an XML qname
-      URI resourceURI = new URI(token.getText());
-
-      if (resourceURI.isOpaque()) {
-        // Attempt qname-to-URI substitution for aliased namespace prefixes
-        URI mapping = (URI) aliasMap.get(resourceURI.getScheme());
-        if (mapping != null) {
-          resourceURI = new URI(mapping + resourceURI.getSchemeSpecificPart());
-        }
-      }
-
-      return resourceURI;
-    }
-    catch (URISyntaxException e) {
-      throw new Error("Bad URI syntax in resource: " + e);
-    }
-  }
-
-  /**
-   * Determines if the stream is compressed by inspecting the fileName extension.
-   *
-   * Returns a new "Compressed" stream if the file is compressed or the original
-   * InputStream if the file is not compressed.
-   *
-   * @param fileName String
-   * @param inputStream InputStream
-   * @throws IOException
-   * @return InputStream
-   */
-  private InputStream adjustForCompression(String fileName,
-      InputStream inputStream) throws IOException {
-
-    //validate
-    if (fileName == null) {
-      throw new IllegalArgumentException("File name is null");
-    }
-    if (inputStream == null) {
-      throw new IllegalArgumentException("InputStream is null");
-    }
-
-    InputStream stream = inputStream;
-
-    // Guess at transfer encoding (compression scheme) based on file extension
-    if (fileName.toLowerCase().endsWith(".gz")) {
-      // The file name ends with ".gz", so assume it's a gzip'ed file
-      stream = new GZIPInputStream(inputStream);
-    }
-    else if (fileName.toLowerCase().endsWith(".zip")) {
-      // The file name ends with ".zip", so assume it's a zip'ed file
-      stream = new ZipInputStream(inputStream);
-    }
-
-    assert stream != null;
-    return stream;
-  }
-
-  /**
-   * Adds a name/value pair to the alias map. This method will add associate a
-   * prefix for a target for subsequent commands, making commands like the
-   * following possible: <PRE>
-   * alias http://purl.org/dc/elements/1.1 as dc;
-   * select $title where $uri dc:title $title ;
-   * </PRE>
-   *
-   * @param aliasPrefix the alias that denotes the target
-   * @param aliasTarget the target associated with the prefix
-   */
-  private void addAliasPair(String aliasPrefix, URI aliasTarget) {
-
-    // validate the aliasPrefix parameter
-    if (aliasPrefix == null) {
-
-      throw new IllegalArgumentException("Null \"aliasPrefix\" " + "parameter");
-    }
-
-    // end if
-    // validate the aliasTarget parameter
-    if (aliasTarget == null) {
-
-      throw new IllegalArgumentException("Null \"aliasTarget\" " + "parameter");
-    }
-
-    // end if
-    // add the pair to the map
-    this.getAliasMap().put(aliasPrefix, aliasTarget);
-  }
-
-  /**
-   * Log the iTQL command to a specified file
-   *
-   * @param command PARAMETER TO DO
-   */
-  private void logItql(String command) {
-
-    // Has this session been constructed for logging.
-    // the constructor initialise this if
-    // system property itql.command.log is set
-    if (itqlLogFile == null) {
-
-      return;
-    }
-
-    try {
-      // has the log file been opened?
-      if (itqlLog == null) {
-        itqlLog = new PrintWriter(new FileWriter(itqlLogFile, true), true);
-      }
-
-      // append the command to the file
-      itqlLog.println(command);
-    }
-    catch (Exception ex) {
-      logger.error("Unable to log itql commands", ex);
-    }
-  }
-
-  private class Lexer2 extends Lexer {
-
-    int commandCount = 0;
-    final LinkedList leftoverTokenList = new LinkedList();
-
-    public Lexer2() {
-      super(null);
-    }
-
-    public int getCommandCount() {
-      return commandCount;
-    }
-
-    public void add(String command) throws LexerException, IOException {
-      Lexer lexer = new Lexer(new PushbackReader(new StringReader(command), 256));
-      Token t;
-      while (! ( (t = lexer.next()) instanceof EOF)) {
-        if (t instanceof TTerminator) {
-          t = new EOF();
-          commandCount++;
-        }
-        leftoverTokenList.add(t);
-      }
-    }
-
-    public Token next() throws LexerException, IOException {
-      return leftoverTokenList.isEmpty() ? new EOF() : (Token) leftoverTokenList.removeFirst();
-    }
-
-    public Token peek() throws LexerException, IOException {
-      return leftoverTokenList.isEmpty() ? new EOF() : (Token) leftoverTokenList.getFirst();
-    }
-
-    public boolean nextCommand() {
-      if (commandCount == 0) {
-        return false;
-      }
-      else {
-        //assert commandCount > 0;
-        commandCount--;
-        return true;
-      }
-    }
-  }
-
-  //
-  // Static methods brought in from the late ConstraintExpressionBuilder
-  //
-
-  /**
-   * Returns the text of the given <code>literal</code>.
-   *
-   * @param literal the literal to retrieve the text from
-   * @return The LiteralText value
-   */
-  public static String getLiteralText(ALiteral literal) {
-
-    // validate the literal parameter
-    if (literal == null) {
-
-      throw new IllegalArgumentException("Null \"literal\" " + "parameter");
-    }
-
-    // end if
-    // the text of the literal
-    StringBuffer literalText = new StringBuffer();
-
-    // get all the strands in this literal
-    List strands = literal.getStrand();
-
-    // add each strand together to make the literal text
-    for (Iterator i = strands.iterator(); i.hasNext(); ) {
-
-      // get the strand
-      PStrand strand = (PStrand) i.next();
-
-      // add the strand to the literal text
-      if (strand instanceof AUnescapedStrand) {
-
-        literalText.append( ( (AUnescapedStrand) strand).getText().getText());
-      }
-      else if (strand instanceof AEscapedStrand) {
-
-        literalText.append( ( (AEscapedStrand) strand).getEscapedtext().getText());
-      } // end if
-
-    } // end for
-
-    // return the text
-    return literalText.toString();
-  }
-
-  //
-  // Public API
-  //
-
-  /**
-   * Builds a {@link org.mulgara.query.ConstraintExpression} object from a
-   * {@link org.mulgara.itql.node.PConstraintExpression}, using an <code>aliasMap</code>
-   * to resolve aliases.
-   *
-   * @param expression a constraint expression from the parser
-   * @return RETURNED VALUE TO DO
-   * @throws QueryException if <code>rawConstraintExpression</code> does not
-   *      represent a valid query
-   * @throws URISyntaxException if the <code>rawConstraintExpression</code>
-   *      contains a resource whose text violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
-   */
-  public ConstraintExpression build(PConstraintExpression expression) throws
-      QueryException, URISyntaxException {
-
-    // validate aliasMap parameter
-    if (aliasMap == null) {
-      throw new IllegalArgumentException("Null \"aliasMap\" parameter");
-    }
-
-    // validate expression parameter
-    if (expression == null) {
-      throw new IllegalArgumentException("Null \"expression\" parameter");
-    }
-
-    // log that we're building a constraint expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building constraint expression from " + expression);
-    }
-
-    // build the contraint expression from the parser input
-    expression.apply( (Switch) builder);
-    ConstraintExpression constraintExpression = builder.
-        getConstraintExpression();
-
-    // log that we've building successfully built a constraint expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Successfully built constraint expression from " +
-                   expression);
-    }
-
-    // return the contraint expression
-    return constraintExpression;
-  }
-
-  /**
-   * Returns an anonymous variable unique for this interpreter.
-   * Note: We really should introduce a new subclass of Variable
-   * that is explicitly anonymous, but for now this will do.
-   */
-  public Variable nextAnonVariable() {
-    return new Variable("av__" + this.anonSuffix++);
-  }
-
-  /**
-   * Builds a HAVING compliant {@link org.mulgara.query.ConstraintExpression} object from a
-   * {@link org.mulgara.itql.node.PConstraintExpression}, using an <code>aliasMap</code>
-   * to resolve aliases.  To comply with a HAVING clause the predicate must be one of:
-   * mulgara:occurs mulgara:occursLessThan mulgara:occursMoreThan.
-   *
-   * @param expression a constraint expression from the parser
-   * @return RETURNED VALUE TO DO
-   * @throws QueryException if <code>rawConstraintExpression</code> does not
-   *      represent a valid query
-   * @throws URISyntaxException if the <code>rawConstraintExpression</code>
-   *      contains a resource whose text violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
-   */
-  private ConstraintHaving buildHaving(PConstraintExpression expression)
-      throws QueryException, URISyntaxException {
-    ConstraintExpression hExpr = build(expression);
-
-    if (hExpr instanceof ConstraintOperation) {
-      throw new QueryException("Having currently supports only one constraint");
-    }
-
-    if (!checkHavingPredicates(hExpr)) {
-      throw new QueryException("Only \"occurs\" predicates can be used in a Having clause");
-    }
-    return (ConstraintHaving) hExpr;
-  }
-
-
-  /**
-   * Checks that all predicates in a constraint expression are valid Having predicates
-   * from {@link SpecialPredicates}.
-   *
-   * @param e The constraint expression to check.
-   * @return true if all constraints have special predicates.
-   */
-  private boolean checkHavingPredicates(ConstraintExpression e) {
-    if (e instanceof Constraint) {
-      return e instanceof ConstraintHaving;
-    } else if (e instanceof ConstraintOperation) {
-      // check all sub expressions
-      Iterator i = ((ConstraintOperation)e).getElements().iterator();
-      while (i.hasNext()) {
-        if (checkHavingPredicates((ConstraintExpression)i.next())) {
-          return false;
-        }
-      }
-      // all sub expressions returned true
-      return true;
-    } else {
-      // An unexpected type
-      return false;
-    }
-  }
-
-
-  /**
-   * Set the active server for a backup given either a server URI or
-   * a model URI.
-   *
-   * @param sourceURI URI
-   */
-
-  private void setBackupServer( URI sourceURI ) throws QueryException {
-
-    //Determine if a model or a server is being backed up.
-    if ( (sourceURI != null)
-      && (sourceURI.getFragment() != null)) {
-
-      // make a note that a model is being backed up
-      if (logger.isDebugEnabled()) {
-
-       logger.debug("Model Found. Backing up model " + sourceURI );
-      }
-
-      //remove fragment from the model URI
-      String fragment = sourceURI.getFragment();
-      String serverURI = sourceURI.toString().replaceAll("#" + fragment, "");
-
-      //create URI for the model's server
-       try {
-
-         URI uri = new URI(serverURI);
-
-         //get session for the model's server.
-         setServerURI(uri);
-
-         //update the session (required if this is the first query)
-         this.updateSession(new ModelResource(uri));
-
-       }
-       catch (URISyntaxException uriException) {
-
-        //this will be caught below
-        throw new QueryException("Could not connect to model's Server.",
-                                  uriException);
-       }
-    }
-    else {
-
-      // log that we're backing up a server
-      if (logger.isDebugEnabled()) {
-
-        logger.debug("Backing up server " + sourceURI );
-      }
-
-     //source is a server.
-     setServerURI(sourceURI);
-    }
-  }
-
-
-  /**
-   * Try to recognise a uri alias, and return the canonical form instead.
-   *
-   * @param uri The URI being checked.
-   * @return The updated URI.  May be the same as the uri parameter.
-   */
-  private URI getCanonicalUriAlias(URI uri) {
-    // only do this for remote protocols
-    if (!"rmi".equals(uri.getScheme()) && !"soap".equals(uri.getScheme())) {
-      return uri;
-    }
-    logger.debug("Checking for an alias on: " + uri);
-    // extract the host name
-    String host = uri.getHost();
-    if (host == null) {
-      return uri;
-    }
-    Set hostnames = getHostnameAliases();
-    // Check with a DNS server to see if this host is recognised
-    InetAddress addr = null;
-    try {
-      addr = InetAddress.getByName(host);
-    } catch (UnknownHostException uhe) {
-      // The host was unknown, so allow resolution to continue as before
-      return uri;
-    }
-    // check the various names against known aliases and the given name
-    if (
-        hostnames.contains(host) ||
-        hostnames.contains(addr.getHostName()) ||
-        hostnames.contains(addr.getCanonicalHostName()) ||
-        hostnames.contains(addr.getHostAddress())
-    ) {
-      // change the host name to one that is recognised
-      // use the system uri to find the local host name
-      URI serverURI = getServerURI();
-      if (serverURI == null) {
-        return uri;
-      }
-      String newHost = serverURI.getHost();
-      try {
-        return new URI(uri.getScheme(), newHost, uri.getPath(), uri.getFragment());
-      } catch (URISyntaxException e) { /* fall through */ }
-    }
-
-    // not found, so return nothing
-    return uri;
-  }
-
-
-  /**
-   * Method to ask the ServerInfo for the local server aliases.
-   * This will return an empty set if ServerInfo is not available -
-   * ie. being run on a host which has no local database, such an an iTQL client.
-   *
-   * @return The set of server aliases as strings
-   */
-  private static Set getHostnameAliases() {
-    Set names = (Set)getServerInfoProperty("HostnameAliases");
-    return (names == null) ? java.util.Collections.EMPTY_SET : names;
-  }
-
-
-  /**
-   * Method to ask the ServerInfo for the local server URI.
-   * This will return null if ServerInfo is not available -
-   * ie. being run on a host which has no local database, such an an iTQL client.
-   *
-   * @return The URI of the local server, or null if this is not a server.
-   */
-  private static URI getServerURI() {
-    return (URI)getServerInfoProperty("ServerURI");
-  }
-
-
-  /**
-   * Method to get the value of a property from the ServerInfo for the local database session.
-   * This will return null if ServerInfo is not available -
-   * ie. being run on a host which has no local database, such an an iTQL client.
-   *
-   * @param property The property to return, with the correct case.
-   * @return The object returned from the accessor method named, or null if ServerInfo is not available.
-   */
-  private static Object getServerInfoProperty(String property) {
-    Object o = null;
-    try {
-      Class rsf = Class.forName("org.mulgara.server.ServerInfo");
-      java.lang.reflect.Method getter = rsf.getMethod("get" + property, null);
-      o = getter.invoke(null, null);
-    } catch (Exception e) { /* no op */ }
-    return o;
-  }
-
-}

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBean.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBean.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBean.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -29,8 +29,8 @@
 
 // Java APIs
 import java.io.*;
+import java.net.MalformedURLException;
 import java.net.URI;
-import java.net.URISyntaxException;
 import java.util.*;
 import javax.xml.soap.SOAPException;
 import org.w3c.dom.*;
@@ -43,13 +43,25 @@
 import org.jrdf.graph.BlankNode;
 
 // Mulgara packages
+import org.mulgara.connection.Connection;
+import org.mulgara.connection.ConnectionException;
 import org.mulgara.itql.lexer.LexerException;
 import org.mulgara.itql.parser.ParserException;
+import org.mulgara.parser.Interpreter;
+import org.mulgara.parser.MulgaraLexerException;
+import org.mulgara.parser.MulgaraParserException;
 import org.mulgara.query.Answer;
 import org.mulgara.query.Query;
 import org.mulgara.query.QueryException;
 import org.mulgara.query.TuplesException;
+import org.mulgara.query.operation.Backup;
+import org.mulgara.query.operation.Command;
+import org.mulgara.query.operation.DataTx;
+import org.mulgara.query.operation.Load;
+import org.mulgara.query.operation.Restore;
+import org.mulgara.query.operation.SetAutoCommit;
 import org.mulgara.query.rdf.LiteralImpl;
+import org.mulgara.query.rdf.Mulgara;
 import org.mulgara.server.Session;
 
 /**
@@ -74,63 +86,53 @@
  */
 public class ItqlInterpreterBean {
 
-  /**
-   * the logging category to log to
-   */
-  private final static Logger log =
-      Logger.getLogger(ItqlInterpreterBean.class.getName());
+  /** The logger */
+  private final static Logger log = Logger.getLogger(ItqlInterpreterBean.class.getName());
 
-  /**
-   * Get line separator.
-   */
+  /** line separator */
   private static final String EOL = System.getProperty("line.separator");
 
   /**
    * The TQL namespace, used when creating an XML response.
-   *
    * TODO: Bring this into line with the Mulgara.NAMESPACE, which may break existing client.
    */
   private final static String TQL_NS = "http://mulgara.org/tql#";
+  
+  /** Dummy load source for RDF files on an input stream. */
+  private final static URI DUMMY_RDF_SOURCE = URI.create(Mulgara.NAMESPACE+"locally-sourced-inputStream.rdf");
 
-  /**
-   * The ITQL interpreter Bean.
-   */
-  private final ItqlInterpreter interpreter =
-    new ItqlInterpreter(ItqlInterpreter.getDefaultAliases());
+  /** The ITQL interpreter Bean. */
+  private final TqlAutoInterpreter interpreter = new TqlAutoInterpreter();
+  
+  /** A legacy session handle. Only used to remember the session a client asked for. */
+  private Session legacySession = null;
+  
+  /** An internal parser.  Only used when a legacy client wants to build their own query. */
+  private Interpreter parser = new TqlInterpreter();
+  
+  /** Indicates that the last command wanted to quit. */
+  private boolean quit = false;
 
   /**
-   * Create the ITQL interpreter.
-   *
-   * The session will be obtained using a
-   *   {@link org.mulgara.server.driver.SessionFactoryFinder}.
+   * Create the TQL interpreter.
    */
   public ItqlInterpreterBean() {
-
-    if (log.isInfoEnabled()) {
-
-      log.info("Created an ItqlInterpreterBean");
-    }
-
+    if (log.isInfoEnabled()) log.info("Created an ItqlInterpreterBean");
   }
 
   /**
-   * Create the ITQL interpreter using the given <code>session</code>.
-   *
+   * @deprecated
+   * Create the TQL interpreter using the given <code>session</code>.
+   * The Session will be ignored.  Security is currently unimplemented, but the domain is recorded.
    * @param session the session to use to communicate with the Mulgara server
    */
   public ItqlInterpreterBean(Session session, URI securityDomain) {
-
     if (log.isInfoEnabled()) {
       log.info("Created an ItqlInterpreterBean with a supplied session and security domain");
     }
-
-    try {
-      interpreter.setSession(session, securityDomain);
-    } catch (QueryException e) {
-
-      interpreter.setLastError(e);
-      interpreter.setLastMessage("Couldn't set interpreter session: " + e.getMessage());
-    }
+    legacySession = session;
+    interpreter.preSeedSession(session);
+    interpreter.setSecurityDomain(securityDomain);
   }
 
   // executeQueryToMap()
@@ -143,7 +145,7 @@
    */
   public static String[] splitQuery(String multiQuery) {
 
-    List singleQueryList = new ArrayList();
+    List<String> singleQueryList = new ArrayList<String>();
 
     // Inside a URI?
     boolean INSIDE_URI = false;
@@ -154,11 +156,8 @@
     // Start index for next single query
     int startIndex = 0;
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("About to break up query: " + multiQuery);
 
-      log.debug("About to break up query: " + multiQuery);
-    }
-
     multiQuery = multiQuery.trim();
 
     // Iterate along the multi query and strip out the single queries.
@@ -172,59 +171,39 @@
         // (OK so maybe it won't appear in a legal URI but let things further
         // down handle this)
         case '\'':
-
           if (!INSIDE_URI) {
-
             if (INSIDE_TEXT) {
-
               // Check for an \' inside a literal
               if ( (lineIndex > 1) && (multiQuery.charAt(lineIndex - 1) != '\\')) {
-
                 INSIDE_TEXT = false;
               }
             } else {
-
               INSIDE_TEXT = true;
             }
           }
-
           break;
 
           // URI start - if not in a literal
         case '<':
-
           if (!INSIDE_TEXT) {
-
             INSIDE_URI = true;
           }
-
           break;
 
           // URI end - if not in a literal
         case '>':
-
           if (!INSIDE_TEXT) {
-
             INSIDE_URI = false;
           }
-
           break;
 
         case ';':
-
           if (!INSIDE_TEXT && !INSIDE_URI) {
-
-            String singleQuery =
-                multiQuery.substring(startIndex, lineIndex + 1).trim();
+            String singleQuery = multiQuery.substring(startIndex, lineIndex + 1).trim();
             startIndex = lineIndex + 1;
             singleQueryList.add(singleQuery);
-
-            if (log.isDebugEnabled()) {
-
-              log.debug("Found single query: " + singleQuery);
-            }
+            if (log.isDebugEnabled()) log.debug("Found single query: " + singleQuery);
           }
-
           break;
 
         default:
@@ -233,38 +212,36 @@
 
     // Lasy query is not terminated with a ';'
     if (startIndex < multiQuery.length()) {
-
       singleQueryList.add(multiQuery.substring(startIndex, multiQuery.length()));
     }
 
-    return (String[]) singleQueryList.toArray(new String[singleQueryList.size()]);
+    return singleQueryList.toArray(new String[singleQueryList.size()]);
   }
 
   /**
    * Returns the session to use to communicate with the Mulgara server.
-   *
-   * @return the session to use to communicate with the Mulgara server
+   * If you need a session, use a {@link ConnectionFactory} instead.
+   * @deprecated The user should not be accessing a session through a
+   * command interpreter.
+   * @return the session to use to communicate with the Mulgara server.  This is probably <code>null</code>.
    */
   public Session getSession() {
-
-    try {
-      return this.interpreter.getSession();
-    } catch (QueryException e) {
-      return null;
-    }
+    return legacySession;
   }
 
   /**
    * Returns the session to use to communicate with the specified Mulgara server.
-   *
+   * @deprecated The user should not be accessing a session through a
+   * command interpreter.
    * @param serverURI URI Server to get a Session for.
-   * @return the session to use to communicate with the specified Mulgara server
+   * @return the session to use to communicate with the specified Mulgara server,
+   * or <code>null</code> if it was not possible to create a session for the URI.
    */
   public Session getSession(URI serverURI) {
-
     try {
-      return this.interpreter.getSession(serverURI);
-    } catch (QueryException e) {
+      return interpreter.establishConnection(serverURI).getSession();
+    } catch (Exception e) {
+      log.error("Unable to get session for: " + serverURI, e);
       return null;
     }
   }
@@ -275,26 +252,16 @@
    *
    * @return the alias namespace map associated with this bean.
    */
-  public Map getAliasMap() {
-
-    return this.interpreter.getAliasMap();
+  @SuppressWarnings("deprecation")
+  public Map<String,URI> getAliasMap() {
+    return this.interpreter.getAliasesInUse();
   }
 
   /**
    * Closes the session underlying this bean.
    */
   public void close() {
-    try {
-      Session session = interpreter.getSession();
-      if (session != null) {
-        session.close();
-      }
-      session = null;
-    } catch (QueryException e) {
-      if (log.isInfoEnabled()) {
-        log.info("Couldn't close interpreter session", e);
-      }
-    }
+    interpreter.close();
   }
 
   //
@@ -304,48 +271,60 @@
   /**
    * Begin a new transaction by setting the autocommit off
    *
-   * @param name the name of the transaction ( debug purposes only )
-   * @throws QueryException EXCEPTION TO DO
+   * @param name the name of the transaction (debug purposes only)
+   * @throws QueryException Error setting up the transaction.
    */
   public void beginTransaction(String name) throws QueryException {
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Begin transaction for :" + name);
 
-      log.debug("Begin transaction for :" + name);
+    if (legacySession != null) legacySession.setAutoCommit(false);
+    SetAutoCommit autocommitCmd = new SetAutoCommit(false);
+    try {
+      // do what the autointerpreter does, but don't worry about the result
+      Connection localConnection = interpreter.getLocalConnection();
+      autocommitCmd.execute(localConnection);
+      interpreter.updateConnectionsForTx(localConnection, autocommitCmd);
+    } catch (QueryException qe) {
+      throw qe;
+    } catch (Exception e) {
+      throw new QueryException("Unable to start a transaction", e);
     }
-
-    this.getSession().setAutoCommit(false);
   }
 
   /**
    * Commit a new transaction by setting the autocommit on
    *
    * @param name the name of the transaction ( debug purposes only ) *
-   * @throws QueryException EXCEPTION TO DO
+   * @throws QueryException Unable to commit one of the connections.
    */
+  @SuppressWarnings("deprecation")
   public void commit(String name) throws QueryException {
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Commit transaction for :" + name);
 
-      log.debug("Commit transaction for :" + name);
-    }
-
     // this is the same as a commit call
-    this.getSession().setAutoCommit(true);
+    if (legacySession != null) legacySession.setAutoCommit(true);
+    interpreter.commitAll();
   }
 
+
   /**
    * Rollback an existing transaction
    *
    * @param name the name of the transaction ( debug purposes only ) *
-   * @throws QueryException EXCEPTION TO DO
+   * @throws QueryException Unable to rollback one of the connections
    */
+  @SuppressWarnings("deprecation")
   public void rollback(String name) throws QueryException {
 
     log.warn("Rollback transaction for :" + name);
 
-    this.getSession().rollback();
-    this.getSession().setAutoCommit(true);
+    if (legacySession != null) {
+      legacySession.rollback();
+      legacySession.setAutoCommit(true);
+    }
+    interpreter.rollbackAll();
   }
 
   /**
@@ -381,14 +360,14 @@
           log.debug("Executing query : " + singleQuery);
         }
 
-        interpreter.executeCommand(singleQuery);
+        executeCommand(singleQuery);
 
         Answer answer = null;
         try {
           answer = this.interpreter.getLastAnswer();
 
           if ((answer == null) || answer.isUnconstrained()) {
-            if (this.interpreter.getLastError() == null) {
+            if (this.interpreter.getLastException() == null) {
               //Not an error, but a message does exist
               Element message =
                   (Element)query.appendChild(doc.createElementNS(TQL_NS, "message"));
@@ -400,10 +379,13 @@
             } else {
               //Error has occurred at the interpreter
               //Generate a SOAP fault
-              // TODO REMOVE Constants.FAULT_CODE_SERVER,
-              log.error("Execute query failed.  Returning error", interpreter.getLastError());
+              System.err.println("Generating a SOAP fault due to interpreter exception:");
+              interpreter.getLastException().printStackTrace();
+              log.error("Execute query failed.  Returning error", interpreter.getLastException());
               throw new SOAPException("ItqlInterpreter error - " +
-                  interpreter.getCause(interpreter.getLastError(), 0));
+                  ItqlUtil.getCause(interpreter.getLastException(), 0));
+              // TODO: consider adding + EOL + "Query: [" + singleQuery + "]");
+              // though must first consider impact on clients
             }
             // Ensure answer is null.
             answer = null;
@@ -427,24 +409,24 @@
     }
   }
 
+
   /**
    * Answer TQL queries.
    *
-   * @param queryString PARAMETER TO DO
+   * @param queryString A query to execute
    * @return the answer String to the TQL query
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General exception type to cover all possible conditions,
+   *         including bad query syntax, network errors, unknown graphs, etc.
    */
   public String executeQueryToString(String queryString) throws Exception {
-
     String result = DOM2Writer.nodeToString(this.execute(queryString), false);
 
-    if (log.isDebugEnabled()) {
-      log.debug("Sending result to caller : " + result);
-    }
+    if (log.isDebugEnabled()) log.debug("Sending result to caller : " + result);
 
     return result;
   }
 
+
   /**
    * Executes a semicolon delimited string of queries. <p>
    *
@@ -469,11 +451,11 @@
    *      org.mulgara.query.Answer}, the messages are {@link
    *      java.lang.String}s
    */
-  public List executeQueryToList(String queryString) {
-
+  public List<Object> executeQueryToList(String queryString) {
     return executeQueryToList(queryString, false);
   }
 
+
   /**
    * Executes a semicolon delimited string of queries. <p>
    *
@@ -492,22 +474,17 @@
    * {@link org.mulgara.query.Answer} or a {@link java.lang.String} (error)
    * message. </p>
    *
-   * @param queryString semi-colon delimited string containing the queries to be
-   *      executed
+   * @param queryString semi-colon delimited string containing the queries to be executed
    * @param keepExceptions return exceptions, don't convert them to a string.
-   * @return a list of answers, messages and errors, answers are of type {@link
-   *      org.mulgara.query.Answer}, the messages are {@link
-   *      java.lang.String}s
+   * @return a list of answers, messages and errors, answers are of type
+   *      {@link org.mulgara.query.Answer}, the messages are {@link java.lang.String}s
    */
-  public List executeQueryToList(String queryString, boolean keepExceptions) {
+  public List<Object> executeQueryToList(String queryString, boolean keepExceptions) {
 
-    List answers = new ArrayList();
+    List<Object> answers = new ArrayList<Object>();
 
-    if (log.isDebugEnabled()) {
+    if (log.isDebugEnabled()) log.debug("Received a TQL query : " + queryString);
 
-      log.debug("Received a TQL query : " + queryString);
-    }
-
     String[] queries = splitQuery(queryString);
 
     for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
@@ -515,21 +492,17 @@
       String singleQuery = queries[queryIndex];
 
       // Resolve the query
-      if (log.isDebugEnabled()) {
+      if (log.isDebugEnabled()) log.debug("Executing query : " + singleQuery);
 
-        log.debug("Executing query : " + singleQuery);
-      }
-
-      // end if
       // execute it
       answers.add(this.executeQueryToNiceResult(singleQuery, keepExceptions));
     }
 
-    // end for
     // Send the answers back to the caller
     return answers;
   }
 
+
   /**
    * Executes a {@link java.util.Map} of queries, returning the results of those
    * queries in a map keyed with the same keys as the input map. <p>
@@ -570,40 +543,34 @@
    * @param queries a map of keys to queries to be executed
    * @return a map of answers and error messages
    */
-  public Map executeQueryToMap(Map queries) {
+  public Map<Object,Object> executeQueryToMap(Map<Object,String> queries) {
 
     // create the answer map
-    HashMap answers = new HashMap();
+    HashMap<Object,Object> answers = new HashMap<Object,Object>();
 
     // iterate over the queries
-    for (Iterator keyIter = queries.keySet().iterator(); keyIter.hasNext(); ) {
+    for (Iterator<Object> keyIter = queries.keySet().iterator(); keyIter.hasNext(); ) {
 
       // get the key and the query
       Object key = keyIter.next();
-      String query = (String) queries.get(key);
+      String query = queries.get(key);
 
       // log the query we're executing
-      if (log.isDebugEnabled()) {
+      if (log.isDebugEnabled()) log.debug("Executing " + key + " -> " + query);
 
-        log.debug("Executing " + key + " -> " + query);
-      }
-
-      // end if
       // execute the query
       answers.put(key, this.executeQueryToNiceResult(query, false));
     }
 
-    // end for
     // return the answers
     return answers;
   }
 
-  // getSession()
 
   /**
    * Builds a {@link org.mulgara.query.Query} from the given <var>query</var>.
    *
-   * @param query PARAMETER TO DO
+   * @param query Command containing a query (<em>select $x $y .....</em>).
    * @return a {@link org.mulgara.query.Query} constructed from the given
    *      <var>query</var>
    * @throws IOException if the <var>query</var> can't be buffered
@@ -611,14 +578,13 @@
    * @throws ParserException if the <var>query</var> is not syntactically
    *      correct
    */
-  public Query buildQuery(String query) throws IOException, LexerException,
-      ParserException {
+  public Query buildQuery(String query) throws IOException, MulgaraLexerException, MulgaraParserException {
+    Command cmd =  parser.parseCommand(query);
+    if (!(cmd instanceof Query)) throw new MulgaraParserException("Command is valid, but is not a query: " + query + "(" + cmd.getClass().getName() + ")");
+    return (Query)cmd;
+  }
 
-    // defer to the interpreter
-    return this.interpreter.parseQuery(query);
 
-  } // buildQuery()
-
   /**
    * Execute an iTQL &quot;update&quot; statement that returns no results.
    * <p>
@@ -634,14 +600,13 @@
   public void executeUpdate(String itql) throws ItqlInterpreterException {
 
     try {
-
-      interpreter.executeCommand(itql);
+      executeCommand(itql);
     } catch (Exception e) {
-
       throw new ItqlInterpreterException(e);
     }
 
-    ItqlInterpreterException exception = interpreter.getLastError();
+    Exception e = interpreter.getLastException();
+    ItqlInterpreterException exception = (e == null) ? null : new ItqlInterpreterException(e);
     Answer answer = interpreter.getLastAnswer();
 
     if (answer != null) {
@@ -649,16 +614,14 @@
       try {
         answer.close();
       } catch (TuplesException te) { /* use the following exception */ }
-      throw new IllegalStateException("The execute update method should not " +
-          "return an Answer object!");
-    }
 
-    if (exception != null) {
-
-      throw exception;
+      throw new IllegalStateException("The execute update method should not return an Answer object!");
     }
+
+    if (exception != null) throw exception;
   }
 
+
   /**
    * Returns true if a quit command has been entered, simply calls the
    * interpreter.isQuitRequested.
@@ -668,7 +631,7 @@
    * @see ItqlInterpreter#isQuitRequested()
    */
   public boolean isQuitRequested() {
-    return interpreter.isQuitRequested();
+    return quit;
   }
 
 
@@ -682,23 +645,21 @@
    * @see ItqlInterpreter#getLastMessage()
    */
   public String getLastMessage() {
-
     return interpreter.getLastMessage();
   }
 
 
   /**
-   * Returns the {@linkplain ItqlInterpreter#getLastError last error} of the
+   * Returns the {@linkplain ItqlInterpreter#getLastException last error} of the
    * interpreter.
    *
    * @return the results of the last command execution, null if the command did
    *      not set any message
    *
-   * @see ItqlInterpreter#getLastError()
+   * @see ItqlInterpreter#getLastException()
    */
-  public ItqlInterpreterException getLastError() {
-
-    return interpreter.getLastError();
+  public ItqlInterpreterException getLastException() {
+    return new ItqlInterpreterException(interpreter.getLastException());
   }
 
 
@@ -710,23 +671,16 @@
    * @throws ItqlInterpreterException if the query fails.
    */
   public Answer executeQuery(String itql) throws ItqlInterpreterException {
-
     try {
-      interpreter.executeCommand(itql);
+      executeCommand(itql);
     } catch (Exception e) {
       throw new ItqlInterpreterException(e);
     }
 
-    ItqlInterpreterException exception = interpreter.getLastError();
+    Exception exception = interpreter.getLastException();
+    if (exception != null) throw new ItqlInterpreterException(exception);
 
-    if (exception != null) {
-
-      throw exception;
-    }
-
-    Answer answer = interpreter.getLastAnswer();
-
-    return answer;
+    return interpreter.getLastAnswer();
   }
 
 
@@ -747,34 +701,27 @@
    * @throws QueryException if the data fails to load or the file does not exist
    * on the local file system.
    */
-  public long load(File sourceFile, URI destinationURI)
-                throws QueryException {
+  public long load(File sourceFile, URI destinationURI) throws QueryException {
+    long numberOfStatements = 0;
 
-    long NumberOfStatements = 0;
-    InputStream inputStream = null;
-
     // check for the local file
-    if ( ! sourceFile.exists() ) {
-      throw new QueryException(sourceFile+" does not exist on the local file "+
-                               "system");
+    if (!sourceFile.exists()) {
+      throw new QueryException(sourceFile+" does not exist on the local file system");
     }
     try {
-      inputStream = sourceFile.toURL().openStream();
-      NumberOfStatements = interpreter.load(inputStream, sourceFile.toURI(), destinationURI);
-    } catch (IOException ex) {
-      throw new QueryException("Unable to read the contents of "+sourceFile, ex );
-    } finally {
-      if (inputStream != null) {
-        try {
-          inputStream.close();
-        } catch (IOException ex) {}
-      }
+      Load loadCmd = new Load(sourceFile.toURI(), destinationURI, true);
+      numberOfStatements = (Long)loadCmd.execute(interpreter.establishConnection(loadCmd.getServerURI()));
+    } catch (QueryException ex) {
+      throw ex;
+    } catch (Exception ex) {
+      throw new QueryException("Unable to load data: " + ex.getMessage(), ex);
     }
-    return NumberOfStatements;
+    return numberOfStatements;
    }
 
- /**
-   * Backup all the data on the specified server or model to a local file.
+
+  /**
+   * Backup all the data on the specified server or model to a client local file.
    * The database is not changed by this method.
    *
    * @param sourceURI The URI of the server or model to backup.
@@ -782,11 +729,18 @@
    * receive the backup contents.
    * @throws QueryException if the backup cannot be completed.
    */
-  public void backup(URI sourceURI, File destinationFile ) throws QueryException {
-
-    interpreter.backup(sourceURI, destinationFile);
+  public void backup(URI sourceURI, File destinationFile) throws QueryException {
+    Backup backup = new Backup(sourceURI, destinationFile.toURI(), true);
+    try {
+      backup.execute(interpreter.establishConnection(backup.getServerURI()));
+    } catch (MalformedURLException e) {
+      throw new QueryException("Bad source graph URI: " + sourceURI, e);
+    } catch (ConnectionException e) {
+      throw new QueryException("Unable to establish connection to: " + backup.getServerURI(), e);
+    }
   }
 
+
   /**
    * Backup all the data on the specified server to an output stream.
    * The database is not changed by this method.
@@ -796,10 +750,16 @@
    * @throws QueryException if the backup cannot be completed.
    */
   public void backup(URI sourceURI, OutputStream outputStream) throws QueryException {
-
-    interpreter.backup(sourceURI, outputStream);
+    URI serverUri = DataTx.calcServerUri(sourceURI);
+    try {
+      Connection conn = interpreter.establishConnection(serverUri);
+      Backup.backup(conn, sourceURI, outputStream);
+    } catch (ConnectionException e) {
+      throw new QueryException("Unable to establish connection to: " + serverUri, e);
+    }
   }
 
+
   /**
    * Load the contents of an InputStream into a database/model.  The method assumes
    * the source to be RDF/XML.
@@ -813,10 +773,10 @@
    * @return number of rows inserted into the destination model
    */
   public long load(InputStream inputStream, URI destinationURI) throws QueryException {
-
-    return interpreter.load(inputStream, destinationURI);
+    return load(inputStream, DUMMY_RDF_SOURCE, destinationURI);
   }
 
+
   /**
    * Load the contents of an InputStream or a URI into a database/model.
    * <p>
@@ -833,12 +793,21 @@
    * @return number of rows inserted into the destination model
    * @throws QueryException if the data fails to load
    */
-  public long load(InputStream inputStream, URI sourceURI, URI destinationURI)
-                throws QueryException {
-
-     return interpreter.load(inputStream, sourceURI, destinationURI);
+  public long load(InputStream inputStream, URI sourceURI, URI destinationURI) throws QueryException {
+    long numberOfStatements = 0;
+    try {
+      Load loadCmd = new Load(sourceURI, destinationURI, true);
+      loadCmd.setOverrideStream(inputStream);
+      numberOfStatements = (Long)loadCmd.execute(interpreter.establishConnection(loadCmd.getServerURI()));
+    } catch (QueryException ex) {
+      throw ex;
+    } catch (Exception ex) {
+      throw new QueryException("Unable to load data: " + ex.getMessage(), ex);
+    }
+    return numberOfStatements;
   }
 
+
   /**
    * Restore all the data on the specified server. If the database is not
    * currently empty then the database will contain the union of its current
@@ -849,9 +818,10 @@
    * @throws QueryException if the restore cannot be completed.
    */
   public void restore(InputStream inputStream, URI serverURI) throws QueryException {
-     interpreter.restore(inputStream, serverURI);
+     restore(inputStream, serverURI, DUMMY_RDF_SOURCE);
   }
 
+
   /**
    * Restore all the data on the specified server. If the database is not
    * currently empty then the database will contain the union of its current
@@ -863,9 +833,16 @@
    * @param sourceURI The URI of the backup file to restore from.
    * @throws QueryException if the restore cannot be completed.
    */
-  public void restore(InputStream inputStream, URI serverURI, URI sourceURI)
-      throws QueryException {
-     interpreter.restore(inputStream, serverURI, sourceURI);
+  public void restore(InputStream inputStream, URI serverURI, URI sourceURI) throws QueryException {
+    try {
+      Restore restoreCmd = new Restore(sourceURI, serverURI, true);
+      restoreCmd.setOverrideStream(inputStream);
+      restoreCmd.execute(interpreter.establishConnection(restoreCmd.getServerURI()));
+    } catch (QueryException ex) {
+      throw ex;
+    } catch (Exception ex) {
+      throw new QueryException("Unable to load data: " + ex.getMessage(), ex);
+    }
   }
 
 
@@ -886,10 +863,7 @@
       Element variables = (Element) parent.appendChild(VARIABLES);
 
       for (int column = 0; column < answer.getVariables().length; column++) {
-
-        Element variable =
-            (Element) variables.appendChild(doc.createElement(
-            answer.getVariables()[column].getName()));
+        variables.appendChild(doc.createElement(answer.getVariables()[column].getName()));
       }
 
       // Add any solutions
@@ -904,9 +878,7 @@
           Object object = answer.getObject(column);
 
           // If the node is null, don't add a tag at all
-          if (object == null) {
-            continue;
-          }
+          if (object == null) continue;
 
           // Otherwise, add a tag for the node
           Element variable =
@@ -949,8 +921,9 @@
     } catch (TuplesException e) {
       throw new QueryException("Couldn't build query", e);
     }
-  } // appendSolutions
+  }
 
+
   //
   // Internal methods
   //
@@ -974,47 +947,40 @@
     try {
 
       // get the answer to the query
-      interpreter.executeCommand(query);
+      executeCommand(query);
       Answer answer = this.interpreter.getLastAnswer();
 
       // log the query response
       if (log.isDebugEnabled()) {
-
         log.debug("Query response message = " + interpreter.getLastMessage());
       }
 
       // end if
       // turn the answer into a form we can handle
       if (answer != null) {
-
         // set this as the answer
         result = answer;
       } else {
 
         // get the error in an appropriate form
-        if (this.interpreter.getLastError() != null) {
+        if (this.interpreter.getLastException() != null) {
 
           // error has occurred at the interpreter
           if (log.isDebugEnabled()) {
-
-            log.debug("Adding query error to map - " +
-                this.interpreter.getLastError());
+            log.debug("Adding query error to map - " + this.interpreter.getLastException());
           }
 
           // end if
           // set this as the answer
           if (keepExceptions) {
-
-            result = this.interpreter.getLastError();
+            result = this.interpreter.getLastException();
           } else {
-
-            result = this.interpreter.getLastError().getMessage();
+            result = this.interpreter.getLastException().getMessage();
           }
         } else {
 
           // log that we're adding the response message
           if (log.isDebugEnabled()) {
-
             log.debug("Adding response message to map - " + interpreter.getLastMessage());
           }
 
@@ -1030,7 +996,6 @@
     } catch (Exception e) {
 
       if (keepExceptions) {
-
         result = e;
       } else {
 
@@ -1039,7 +1004,6 @@
         Throwable lastCause = e;
 
         while (cause != null) {
-
           lastCause = cause;
           cause = cause.getCause();
         }
@@ -1049,7 +1013,6 @@
         String exceptionMessage = lastCause.getMessage();
 
         if (exceptionMessage == null) {
-
           exceptionMessage = lastCause.toString();
         }
 
@@ -1059,7 +1022,6 @@
 
         // log the message
         if (log.isDebugEnabled()) {
-
           log.debug(exceptionMessage);
         }
 
@@ -1079,55 +1041,39 @@
       }
     }
 
-    // try-catch
-    // return the result
     return result;
   }
 
+
   /**
-    * Sets the serverURI of the interpreter.
+    * Sets the serverURI of the interpreter.  This method now does nothing.
     * @param serverURI The new URI of the server for the interpreter
+    * @deprecated Establishing communication with a server now requires a connection.
+    * Connections can be evaluated automatically with the TqlAutoInterpreter.
     */
   public void setServerURI(String serverURI) {
-
-    try {
-
-      // Set the server URI of the interpreter
-      interpreter.setServerURI((serverURI == null) ? null : new URI(serverURI));
-    } catch (URISyntaxException uriSyntaxException) {
-
-      log.error("Could not change server due to bad uri syntax.",
-                uriSyntaxException);
-
-      // Set the last error to be the syntax exception
-      interpreter.setLastError(uriSyntaxException);
-    } catch (QueryException queryException) {
-
-      log.error("Could not change the server due to a query exception.",
-                queryException);
-
-      // Set the last error to be a query exception
-      interpreter.setLastError(queryException);
-    }
+    // Do nothing
   }
 
+
   /**
    * Sets the aliases associated with this bean.
    *
    * @param aliasMap the alias map associated with this bean
    */
-  public void setAliasMap(HashMap aliasMap) {
-
-    this.interpreter.setAliasMap(aliasMap);
+  @SuppressWarnings("deprecation")
+  public void setAliasMap(HashMap<String,URI> aliasMap) {
+    ((TqlInterpreter)parser).setAliasMap(aliasMap);
+    interpreter.setAliasesInUse(aliasMap);
   }
 
   /**
     * Clears the last error of the interpreter.
     */
+  @SuppressWarnings("deprecation")
   public void clearLastError() {
-
     // Set the last error to be null
-    interpreter.setLastError(null);
+    interpreter.clearLastException();
   }
 
  /**
@@ -1136,15 +1082,20 @@
   * container or the user has not called close().
   */
   protected void finalize() throws Throwable {
-
     try {
-
       // close the interpreter session
       this.close();
-
     } finally {
-
       super.finalize();
     }
   }
+
+
+  /**
+   * Executes the requested command, and records if the command wants to quit.
+   * @param command The command to execute.
+   */
+  private void executeCommand(String command) {
+    quit = !interpreter.executeCommand(command);
+  }
 }

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -82,32 +82,19 @@
   // Members
   //
 
-  /**
-   * the category to send logging info to
-   *
-   */
-  private static Category log =
-      Category.getInstance(ItqlInterpreterBeanUnitTest.class.getName());
+  /** The category to send logging info to */
+  private static Category log = Category.getInstance(ItqlInterpreterBeanUnitTest.class.getName());
 
-  /**
-   * Description of the Field
-   *
-   */
+  /** Description of the Field */
   private ItqlInterpreterBean bean = null;
 
-  /**
-   * host name of server
-   */
+  /** host name of server */
   private static String hostName = System.getProperty("host.name");
 
-  /**
-   * an example model
-   */
+  /** an example model */
   private static String testModel = "rmi://" + hostName + "/server1#itqlmodel";
 
-  /**
-   * Data directory for test files
-   */
+  /** Data directory for test files */
   private static String dataDirectory = System.getProperty("cvs.root") + "/data";
 
   static {
@@ -116,16 +103,9 @@
     }
   }
 
-  /**
-   * a temp directory location
-   */
+  /** a temp directory location */
   private static File tmpDirectory = TempDir.getTempDir();
 
-  /**
-   * location of test directory
-   */
-  private static String testDir = System.getProperty("test.dir");
-
   //
   // Public API
   //
@@ -142,17 +122,11 @@
 
     // load the logging configuration
     try {
-
-      DOMConfigurator.configure(System.getProperty("cvs.root") +
-          "/log4j-conf.xml");
+      DOMConfigurator.configure(System.getProperty("cvs.root") + "/log4j-conf.xml");
+    } catch (FactoryConfigurationError fce) {
+      log.error("Unable to configure logging service from XML configuration file");
     }
-    catch (FactoryConfigurationError fce) {
 
-      log.error("Unable to configure logging service from XML configuration " +
-          "file");
-    }
-
-    // try-catch
   }
 
   /**
@@ -193,7 +167,7 @@
    * The main program for the ItqlInterpreterBeanUnitTest class
    *
    * @param args The command line arguments
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General catch-all for exceptions thrown during the entire test suite
    */
   public static void main(String[] args) throws Exception {
 
@@ -222,7 +196,7 @@
   /**
    * A unit test for JUnit
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General catch-all for exceptions thrown during the test
    */
   public void testQuery2() throws Exception {
 
@@ -237,7 +211,7 @@
   /**
    * A unit test for JUnit
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General catch-all for exceptions thrown during the test
    */
   public void testQuery3() throws Exception {
 
@@ -258,10 +232,8 @@
       log.error("\nDIRECT:'" + directAnswer + "'");
       log.error("\nSOAP  :'" + soapAnswer + "'");
       log.error("\nEQUALS  :'" + soapAnswer.equals(directAnswer) + "'");
-      log.error("\nSSTARTS  :'" + soapAnswer.startsWith(directAnswer) +
-          "'");
-      log.error("\nDSTARTS  :'" + directAnswer.startsWith(soapAnswer) +
-          "'");
+      log.error("\nSSTARTS  :'" + soapAnswer.startsWith(directAnswer) + "'");
+      log.error("\nDSTARTS  :'" + directAnswer.startsWith(soapAnswer) + "'");
     }
 
     assertEquals("A insert SOAP iTQL result is not the same as a direct call",
@@ -273,7 +245,7 @@
    * A unit test for JUnit. Tests that an Answer can be obtained and
    * iterated over and reset multiple times.
    *
-   * @throws Exception EXCEPTION TO DO
+   * @throws Exception General catch-all for exceptions thrown during the test
    */
   public void testAnswerIteration() throws Exception {
 
@@ -329,17 +301,16 @@
   }
 
   /**
-   * METHOD TO DO
+   * Performs a query over the SOAP interface
    *
-   * @param query PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
-   * @throws Exception EXCEPTION TO DO
+   * @param query The TQL query to execute over the interface.
+   * @return The XML response to the call, as a string.
+   * @throws Exception General catch-all for exceptions thrown during the call
    */
   public String executeSoapCall(String query) throws Exception {
 
     //URL url = new URL("http://" + hostName + ":8080/soap/servlet/rpcrouter");
-    URL url = new URL("http://" + hostName +
-        ":8080/webservices/services/ItqlBeanService");
+    URL url = new URL("http://" + hostName + ":8080/webservices/services/ItqlBeanService");
 
     // Build the call.
     Call call = new Call();
@@ -349,7 +320,7 @@
     //call.setEncodingStyleURI(Constants.NS_URI_LITERAL_XML);
     call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
 
-    Vector params = new Vector();
+    Vector<Parameter> params = new Vector<Parameter>();
     params.addElement(new Parameter("queryString", String.class, query,
         Constants.NS_URI_SOAP_ENC));
     call.setParams(params);
@@ -369,8 +340,7 @@
           " Fault String = " + fault.getFaultString());
 
       return fault.getFaultCode() + " - " + fault.getFaultString();
-    }
-    else {
+    } else {
 
       Parameter result = resp.getReturnValue();
 
@@ -426,8 +396,7 @@
     // execute the load remotely
     long statements = bean.load(null, sourceURI, modelURI);
 
-    this.assertEquals("Incorrect number of statements inserted", 146,
-        statements);
+    assertEquals("Incorrect number of statements inserted", 146, statements);
   }
 
   // testLoadApi1()
@@ -458,8 +427,7 @@
     long statements = bean.load(inputStream,
         sourceURI, modelURI);
 
-    this.assertEquals("Incorrect number of statements inserted", 146,
-        statements);
+    assertEquals("Incorrect number of statements inserted", 146, statements);
 
     inputStream.close();
 
@@ -486,8 +454,7 @@
     long statements = bean.load(sourceURI.toURL().openStream(),
         dummyURI, modelURI);
 
-    this.assertEquals("Incorrect number of statements inserted", 146,
-        statements);
+    assertEquals("Incorrect number of statements inserted", 146, statements);
 
   }
 
@@ -508,8 +475,7 @@
     long statements = bean.load(sourceURI.toURL().openStream(),
         modelURI);
 
-    this.assertEquals("Incorrect number of statements inserted", 146,
-        statements);
+    assertEquals("Incorrect number of statements inserted", 146, statements);
 
   }
 
@@ -529,8 +495,7 @@
     // execute the load locally
     long statements = bean.load(source, modelURI);
 
-    this.assertEquals("Incorrect number of statements inserted", 1482,
-        statements);
+    assertEquals("Incorrect number of statements inserted", 1482, statements);
 
   }
 
@@ -550,8 +515,7 @@
     // execute the load locally
     long statements = bean.load(source, modelURI);
 
-    this.assertEquals("Incorrect number of statements inserted", 103,
-        statements);
+    assertEquals("Incorrect number of statements inserted", 103, statements);
 
   }
 
@@ -572,13 +536,12 @@
 
     // execute the load locally
     try {
-      long statements = bean.load(source, modelURI);
-    }
-    catch (QueryException ex) {
+      bean.load(source, modelURI);
+    } catch (QueryException ex) {
       badFile = true;
     }
 
-    this.assertTrue("Excepting a bad file", badFile);
+    assertTrue("Excepting a bad file", badFile);
 
   }
 
@@ -598,7 +561,7 @@
     // execute the load locally
     long statements = bean.load(source, modelURI);
 
-    this.assertEquals("Incorrect number of statements inserted", 99, statements);
+    assertEquals("Incorrect number of statements inserted", 99, statements);
 
   }
 
@@ -620,8 +583,7 @@
       // execute the load locally
       long statements = bean.load(source, modelURI);
 
-      this.assertEquals("Incorrect number of statements inserted", 512,
-          statements);
+      assertEquals("Incorrect number of statements inserted", 512, statements);
     } catch (Exception exception) {
 
       exception.printStackTrace();
@@ -647,7 +609,7 @@
 
     bean.backup(modelURI, file);
 
-    this.assertTrue("Excepting a backup file", file.exists());
+    assertTrue("Excepting a backup file", file.exists());
 
   }
 
@@ -669,7 +631,7 @@
 
     bean.backup(serverURI, file);
 
-    this.assertTrue("Excepting a backup file", file.exists());
+    assertTrue("Excepting a backup file", file.exists());
 
   }
 
@@ -691,7 +653,7 @@
 
     bean.backup(modelURI, new FileOutputStream(file));
 
-    this.assertTrue("Excepting a backup file", file.exists());
+    assertTrue("Excepting a backup file", file.exists());
 
   }
 
@@ -713,7 +675,7 @@
 
     bean.backup(serverURI, new FileOutputStream(file));
 
-    this.assertTrue("Excepting a backup file", file.exists());
+    assertTrue("Excepting a backup file", file.exists());
 
   }
 
@@ -775,23 +737,23 @@
 
     // select the statement
     Answer answer = bean.executeQuery(select);
-    this.assertTrue("Excepting a answer before restore", answer != null);
-    this.assertTrue("Excepting a single result and found :" +
+    assertTrue("Excepting a answer before restore", answer != null);
+    assertTrue("Excepting a single result and found :" +
         answer.getRowCount(), (answer.getRowCount() == 3));
 
     //backup the server
     File file = new File(tmpDirectory, "roundtrip.gz");
     file.delete();
     bean.backup(serverURI, new FileOutputStream(file));
-    this.assertTrue("Excepting a backup file", file.exists());
+    assertTrue("Excepting a backup file", file.exists());
 
     // restore the server
     bean.restore(file.toURL().openStream(), serverURI);
 
     // select the statement
     answer = bean.executeQuery(select);
-    this.assertTrue("Excepting a answer after restore", answer != null);
-    this.assertTrue("Excepting a single result and found :" +
+    assertTrue("Excepting a answer after restore", answer != null);
+    assertTrue("Excepting a single result and found :" +
         answer.getRowCount(), (answer.getRowCount() == 3));
 
   }
@@ -824,7 +786,8 @@
         "/server1#> where $s $p $o;";
 
     // create a 100 beans
-    for (int count = 1; count < 1000; count++) {
+    // TODO: change back to 1000
+    for (int count = 1; count < 100; count++) {
       ItqlInterpreterBean bean = null;
       Answer answer = null;
       try {
@@ -838,15 +801,14 @@
         assertTrue("Failed to query system model", answer.getRowCount() > 0);
         answer.close();
 
-      }
-      catch (Exception ex) {
-        log.error("Failed to create/query the " + count +
-            " ItqlInterpreterBean", ex);
-        assertTrue("Failed to create/query the " + count +
-            " ItqlInterpreterBean", false);
+      } catch (Exception ex) {
+        log.error("Failed to create/query the " + count + " ItqlInterpreterBean", ex);
+        System.err.println("Failed to create/query the " + count + " ItqlInterpreterBean");
+        System.err.println("Exception: " + ex.getMessage());
+        ex.printStackTrace();
+        assertTrue("Failed to create/query the " + count + " ItqlInterpreterBean", false);
         break;
-      }
-      finally {
+      } finally {
         bean.close();
       }
     }
@@ -879,8 +841,7 @@
     if (bean != null) {
       try {
         bean.close();
-      }
-      finally {
+      } finally {
         bean = null;
       }
     }

Deleted: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,2440 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public License
- * Version 1.1 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- *
- * The Original Code is the Kowari Metadata Store.
- *
- * The Initial Developer of the Original Code is Plugged In Software Pty
- * Ltd (http://www.pisoftware.com, mailto:info at pisoftware.com). Portions
- * created by Plugged In Software Pty Ltd are Copyright (C) 2001,2002
- * Plugged In Software Pty Ltd. All Rights Reserved.
- *
- * Contributor(s): N/A.
- *
- * [NOTE: The text of this Exhibit A may differ slightly from the text
- * of the notices in the Source Code files of the Original Code. You
- * should use the text of this Exhibit A rather than the text found in the
- * Original Code Source Code for Your Modifications.]
- *
- */
-
-package org.mulgara.itql;
-
-// third party packages
-import junit.framework.*;
-
-// Java 2 standard packages
-import java.io.*;
-import java.net.*;
-import java.sql.ResultSet;
-import java.util.*;
-import java.rmi.server.UnicastRemoteObject;
-
-import javax.xml.parsers.*;
-
-import org.apache.log4j.Category;
-import org.apache.log4j.xml.DOMConfigurator;
-
-// automagically generated classes
-import org.mulgara.itql.parser.ParserException;
-import org.mulgara.query.Answer;
-import org.mulgara.query.AnswerImpl;
-import org.mulgara.query.Constraint;
-import org.mulgara.query.ConstraintExpression;
-import org.mulgara.query.ConstraintHaving;
-import org.mulgara.query.ConstraintImpl;
-import org.mulgara.query.ConstraintOccurs;
-import org.mulgara.query.ModelExpression;
-import org.mulgara.query.ModelResource;
-import org.mulgara.query.Query;
-import org.mulgara.query.UnconstrainedAnswer;
-import org.mulgara.query.Variable;
-import org.mulgara.query.rdf.LiteralImpl;
-import org.mulgara.query.rdf.URIReferenceImpl;
-import org.mulgara.util.ResultSetRow;
-import org.mulgara.util.TempDir;
-import org.mulgara.util.TestResultSet;
-
-// emory util package
-import edu.emory.mathcs.util.remote.io.*;
-import edu.emory.mathcs.util.remote.io.server.impl.*;
-
-/**
- * Unit test for {@link ItqlInterpreterUnitTest}. <p>
- *
- * Note. Constraint disjunctions have not yet been implemented, so for now will
- * give the same answers as conjunctions. Hence test results will be <strong>
- * WRONG</strong> once disjunctions are implemented. </p>
- *
- * @created 2001-08-27
- *
- * @author Tom Adams
- *
- * @version $Revision: 1.11 $
- *
- * @modified $Date: 2005/06/26 12:48:09 $ by $Author: pgearon $
- *
- * @company <a href="mailto:info at PIsoftware.com">Plugged In Software</a>
- *
- * @copyright &copy;2001 <a href="http://www.pisoftware.com/">Plugged In
- *      Software Pty Ltd</a>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlInterpreterUnitTest extends TestCase {
-
-  //
-  // Members
-  //
-
-  /**
-   * the category to send logging info to
-   */
-  private static Category log =
-      Category.getInstance(ItqlInterpreterUnitTest.class.getName());
-
-  /**
-   * Get line separator.
-   */
-  private static final String eol = System.getProperty("line.separator");
-
-  /**
-   * Schema namespace.
-   */
-  private static final String rdfSchemaNamespace =
-      "http://www.w3.org/2000/01/rdf-schema#";
-
-  /**
-   * the ITQL command interpreter
-   */
-  private static ItqlInterpreter interpreter = null;
-
-  /**
-   * the URI of the dublin core schema
-   */
-  private static URI dcSchemaURI = null;
-
-  /**
-   * an example model
-   */
-  private static String testModel = null;
-
-  /**
-   * a temp directory location
-   */
-  private static final File tmpDirectory = TempDir.getTempDir();
-
-  /**
-    * host name of server
-    */
-   private static String hostName = System.getProperty("host.name");
-
-  /**
-   * Server1
-   */
-  private static String server = "rmi://"+hostName+"/server1";
-
-  //
-  // Public API
-  //
-
-  /**
-   * Constructs a new ItqlInterpreter unit test.
-   *
-   * @param name the name of the test
-   */
-  public ItqlInterpreterUnitTest(String name) {
-
-    // delegate to super class constructor
-    super(name);
-
-    // load the logging configuration
-    try {
-
-      DOMConfigurator.configure(System.getProperty("cvs.root") +
-                                "/log4j-conf.xml");
-    }
-    catch (FactoryConfigurationError fce) {
-
-      log.error("Unable to configure logging service from XML configuration " +
-                "file");
-    }
-
-    // try-catch
-  }
-
-  // setUp()
-
-  /**
-   * Returns a test suite containing the tests to be run.
-   *
-   * @return the test suite
-   */
-  public static TestSuite suite() {
-
-    TestSuite suite = new TestSuite();
-
-    suite.addTest(new ItqlInterpreterUnitTest("testHelp"));
-    suite.addTest(new ItqlInterpreterUnitTest("testQuit"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSu1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testAlias1"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect3"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect4"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect5"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect6"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect7"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSelect8"));
-    suite.addTest(new ItqlInterpreterUnitTest("testDirectory1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testCreate1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testDrop1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testDelete1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testDelete2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testInsert1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testInsert2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad3"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad4"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad5"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad6"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad7"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad8"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoad9"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSet1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testSet2"));
-    suite.addTest(new ItqlInterpreterUnitTest("test1ParseQuery"));
-    suite.addTest(new ItqlInterpreterUnitTest("test2ParseQuery"));
-    suite.addTest(new ItqlInterpreterUnitTest("test3ParseQuery"));
-    suite.addTest(new ItqlInterpreterUnitTest("test4ParseQuery"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testBackup1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testRestore1"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testCreate3"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoadApi1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoadApi2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoadApi3"));
-    suite.addTest(new ItqlInterpreterUnitTest("testLoadApi4"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testBackupApi1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testBackupApi2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testBackupApi3"));
-    suite.addTest(new ItqlInterpreterUnitTest("testBackupApi4"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testLoadBackupApi1"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testRestoreApi1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testRestoreApi2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testRestoreApi3"));
-
-    suite.addTest(new ItqlInterpreterUnitTest("testBackupRestore1"));
-    suite.addTest(new ItqlInterpreterUnitTest("testBackupRestore2"));
-    suite.addTest(new ItqlInterpreterUnitTest("testBackupRestore3"));
-
-    return suite;
-  }
-
-  /**
-   * Default text runner.
-   *
-   * @param args the command line arguments
-   */
-  public static void main(String[] args) {
-
-    junit.textui.TestRunner.run(suite());
-  }
-
-  // suite()
-  //
-  // Test cases
-  //
-
-  /**
-   * Test the interpreter using a help statement. Executes the following query:
-   * <pre>
-   * help ;
-   * </pre> Expects results: <pre>
-   *
-   *   Valid commands are:
-   *
-   *     su       authenticate a user
-   *     set      set a property
-   *     execute  execute an iTQL script
-   *     alias    define an alias
-   *     create   create a model
-   *     commit   commits a transaction
-   *     drop     drop an entire resource
-   *     insert   insert a set of triples
-   *     delete   delete a set of triples
-   *     load     load contents of a file
-   *     backup   backup the contents of a server to a file
-   *     restore  restore a server from a backup file
-   *     rollback rolls back a transaction
-   *     select   perform a query
-   *     set      sets various options
-   *     quit     end the ITQL session
-   *     help     display this help screen
-   *
-   *   You can also get detailed help on each command:
-   *
-   *     $ help <command> ;
-   *
-   *   For example, to display help on the select command:
-   *
-   *     $ help select ;
-   *
-   *   Note. All commands must be terminated with ";".
-   *
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testHelp() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting help test");
-
-    // create the statement
-    String statement = "help ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-
-    String results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    StringBuffer expected = new StringBuffer();
-    expected.append(eol + "Valid commands are:" + eol + eol);
-    expected.append("  su       authenticate a user" + eol);
-    expected.append("  set      set a property" + eol);
-    expected.append("  execute  execute an iTQL script" + eol);
-    expected.append("  alias    define an alias" + eol);
-    expected.append("  create   create a model" + eol);
-    expected.append("  commit   commits a transaction" + eol);
-    expected.append("  drop     drop an entire resource" + eol);
-    expected.append("  insert   insert a set of triples" + eol);
-    expected.append("  delete   delete a set of triples" + eol);
-    expected.append("  load     load contents of a file          " + eol);
-    expected.append("  backup   backup the contents of a server to a file" + eol);
-    expected.append("  restore  restore a server from a backup file" + eol);
-    expected.append("  rollback rolls back a transaction" + eol);
-    expected.append("  select   perform a query" + eol);
-    expected.append("  set      sets various options" + eol);
-    expected.append("  apply    applies a set of rules" + eol);
-    expected.append("  quit     end the ITQL session" + eol);
-    expected.append("  help     display this help screen" + eol + eol);
-    expected.append("You can also get detailed help on each command:" + eol + eol);
-    expected.append("  $ help <command> ;" + eol + eol);
-    expected.append("For example, to display help on the select command:" + eol + eol);
-    expected.append("  $ help select ;" + eol + eol);
-    expected.append("Note. All commands must be terminated with \";\"." + eol);
-
-    // check that the result are what we expected
-    assertEquals(expected.toString(), results);
-
-    // log that we've completed the test
-    log.info("Completed help test");
-  }
-
-  /**
-   * Test the interpreter using an insert statement. Executes the following query:
-   * <pre>
-   *   insert $s $p $o into &lt;rmi://localhost/database#model&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testInsert1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting insert test 1");
-
-    String statement;
-
-    // create the statement
-    statement = "insert $s $p $o into <file://foo/bar.txt> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    String expected = "Could not insert statements into file://foo/bar.txt" +
-        eol + "Predicate must be a valid URI";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed insert test 1");
-  }
-
-  /**
-   * Test the interpreter using an insert statement. Executes the following query:
-   * <pre>
-   *   insert $s <urn:foo:bar> $o into &lt;rmi://localhost/database#model&gt; ;
-   * </pre> Expects results: 1 inserted statements with the subject and object
-   *   as a new blank node each and a fixed predicate.
-   *
-   * @throws Exception if the test fails
-   */
-  public void testInsert2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting insert test 1");
-
-    String statement;
-
-    // create the statement
-    statement = "create <rmi://localhost/server1#database> ; " + eol +
-        "insert $s <urn:foo:bar> $o into <rmi://localhost/server1#database> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    String expected = "Successfully inserted statements into rmi://localhost/server1#database";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    statement = "drop <rmi://localhost/server1#database> ;";
-    interpreter.executeCommand(statement);
-
-    // log that we've completed the test
-    log.info("Completed insert test 2");
-  }
-
-  // testHelp()
-
-  /**
-   * Test the interpreter using a quit statement. Executes the following query:
-   * <pre>
-   *   quit ;
-   * </pre> Expects results: <pre>
-   *  Quitting ITQL session
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testQuit() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting quit test");
-
-    // create the statement
-    String statement = "quit ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-
-    String results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    String expected = "Quitting ITQL session";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log that we've completed the test
-    log.info("Completed quit test");
-  }
-
-  // testQuit()
-
-  /**
-   * Test the interpreter using an su statement. Executes the following query:
-   * <pre>
-   *   su fred Fo0B at r ;
-   * </pre> Expects results: <pre>
-   *   su is not currently implemented
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSu1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting su test 1");
-
-    // create the statement
-    String statement = "su <ldap://bar.org> fred Fo0Bar ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    String expected = "Credential presented";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log that we've completed the test
-    log.info("Completed su test 1");
-  }
-
-  // testSu1()
-
-  /**
-   * Test the interpreter using an alias statement. Executes the following
-   * query: <pre>
-   *   alias &lt;http://purl.org/dc/elements/1.1&gt; as dc;
-   * </pre> Expects results: <pre>
-   *  Successfully aliased http://purl.org/dc/elements/1.1 as dc
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testAlias1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting alias test 1");
-
-    // create the statement
-    String statement = "alias <http://purl.org/dc/elements/1.1> as dc ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    String results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    String expected =
-        "Successfully aliased http://purl.org/dc/elements/1.1 " + "as dc";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log that we've completed the test
-    log.info("Completed alias test 1");
-  }
-
-  // testAlias1()
-
-  /**
-   * Test the interpreter using a select statement. Executes the following
-   * query: <pre>
-   * select $x from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; where $x
-   * &lt;http://www.w3.org/2000/01/rdf-schema#label&gt; 'Title' ; </pre> Expects
-   * results: <pre>
-   *   x=http://purl.org/dc/elements/1.1/title
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 1");
-
-    // create the statement
-    String statement =
-        "select $x from <" + dcSchemaURI + "> where $x <" + rdfSchemaNamespace +
-        "label> 'Title' ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = new AnswerImpl(interpreter.getLastAnswer());
-
-    // log the results
-    if (log.isDebugEnabled()) {
-      log.debug("Received results : " + results);
-    }
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x", new URIReferenceImpl(new URI(
-        "http://purl.org/dc/elements/1.1/title")));
-
-    Answer expected = new AnswerImpl(trs);
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 1");
-  }
-
-  // testSelect1()
-
-  /**
-   * Test the interpreter using a select statement. Executes the following
-   * query: <pre>
-   * select $x from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; where ($x
-   * &lt;http://www.w3.org/2000/01/rdf-schema#label&gt; 'Title') ; </pre>
-   * Expects results: <pre>
-   *   x=http://purl.org/dc/elements/1.1/title
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 2");
-
-    // create the statement
-    String statement =
-        "select $x from <" + dcSchemaURI + "> where ($x <" +
-        rdfSchemaNamespace + "label> 'Title') ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = interpreter.getLastAnswer();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x", new URIReferenceImpl(new URI(
-        "http://purl.org/dc/elements/1.1/title")));
-
-    Answer expected = new AnswerImpl(trs);
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 2");
-  }
-
-  // testSelect2()
-
-  /**
-   * Test the interpreter using a select statement. Executes the following
-   * query: <pre>
-   * select $x $y from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; where ($x
-   * $y 'Subject'); </pre> Expects results: <pre>
-   *   x=http://purl.org/dc/elements/1.1/subject
-   *   y=http://www.w3.org/2000/01/rdf-schema#label
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect3() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 3");
-
-    // create the statement
-    String statement =
-        "select $x $y from <" + dcSchemaURI + "> where ($x $y 'Subject') ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = interpreter.getLastAnswer();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x",
-                  new URIReferenceImpl(new URI(
-        "http://purl.org/dc/elements/1.1/subject")));
-    row.setObject("y",
-                  new URIReferenceImpl(new URI(
-        "http://www.w3.org/2000/01/rdf-schema#label")));
-
-    Answer expected = new AnswerImpl(trs);
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 3");
-  }
-
-  // testSelect3()
-
-  /**
-   * Test the interpreter using a select statement. Executes the following
-   * query: <pre>
-       * select $x $y from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; where (($x
-   * $y 'Subject') and ($x &lt;http://www.w3.org/2000/01/rdf-schema#label&gt;
-   * 'Subject')) ; </pre> Expects results: <pre>
-   *   x=http://purl.org/dc/elements/1.1/subject
-   *   y=http://www.w3.org/2000/01/rdf-schema#label
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect4() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 4");
-
-    // create the statement
-    String statement =
-        "select $x $y from <" + dcSchemaURI +
-        "> where (($x $y 'Subject') and ($x <" + rdfSchemaNamespace +
-        "label> 'Subject')) ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = interpreter.getLastAnswer();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x", new URIReferenceImpl(
-        new URI("http://purl.org/dc/elements/1.1/subject")));
-    row.setObject("y", new URIReferenceImpl(new URI(
-        "http://www.w3.org/2000/01/rdf-schema#label")));
-
-    Answer expected = new AnswerImpl(trs);
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 4");
-  }
-
-  // testSelect4()
-
-  /**
-   * Test the interpreter using a select statement. Executes the following
-   * query: <pre>
-   * select $x $y from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; where (($x
-   * $y 'Subject') or ($x &lt;http://www.w3.org/2000/01/rdf-schema#label&gt;
-   * 'Subject')) ; </pre> Expects results: <pre>
-   *   x=http://purl.org/dc/elements/1.1/subject
-   *   y=http://www.w3.org/2000/01/rdf-schema#label
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect5() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 5");
-
-    // create the statement
-    String statement =
-        "select $x $y from <" + dcSchemaURI +
-        "> where (($x $y 'Subject') or ($x <" + rdfSchemaNamespace +
-        "label> 'Subject')) ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = new AnswerImpl(interpreter.getLastAnswer());
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x", new URIReferenceImpl(new URI(
-        "http://purl.org/dc/elements/1.1/subject")));
-    row.setObject("y", null);
-    row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x", new URIReferenceImpl(new URI(
-        "http://purl.org/dc/elements/1.1/subject")));
-    row.setObject("y", new URIReferenceImpl(new URI(
-        "http://www.w3.org/2000/01/rdf-schema#label")));
-
-    Answer expected = new AnswerImpl(trs);
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 5");
-  }
-
-  // testSelect5()
-
-  /**
-   * Test the interpreter using a select statement. Executes the following
-   * query: <pre>
-   * select $x $y from <file:<it>mulgarahome</it> /data/dc.rdfs&gt; where (($x $y
-   * 'Subject') and ($x &lt;http://www.w3.org/2000/01/rdf-schema#label&gt;
-   * 'Subject')) and &lt;http://purl.org/dc/elements/1.1/subject&gt; $y
-   * 'Subject' ; </pre> Expects results: <pre>
-   *   x=http://purl.org/dc/elements/1.1/subject
-   *   y=http://www.w3.org/2000/01/rdf-schema#label
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect6() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 6");
-
-    // create the statement
-    String statement =
-        "select $x $y from <" + dcSchemaURI +
-        "> where (($x $y 'Subject') and ($x <" + rdfSchemaNamespace +
-        "label> 'Subject'))" +
-        "and <http://purl.org/dc/elements/1.1/subject> $y 'Subject' ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = interpreter.getLastAnswer();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x",
-                  new URIReferenceImpl(new URI(
-        "http://purl.org/dc/elements/1.1/subject")));
-    row.setObject("y",
-                  new URIReferenceImpl(new URI(
-        "http://www.w3.org/2000/01/rdf-schema#label")));
-
-    Answer expected = new AnswerImpl(trs);
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 6");
-  }
-
-  // testSelect6()
-
-  /**
-   * Test the interpreter using a select statement. Executes the following
-   * query: <pre>
-   * select $x $y from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; where (($x
-   * $y 'Subject') and ($x &lt;http://www.w3.org/2000/01/rdf-schema#label&gt;
-   * 'Subject')) or &lt;http://purl.org/dc/elements/1.1/subject&gt; $y 'Subject'
-   * ; </pre> Expects results: <pre>
-   *   x=http://purl.org/dc/elements/1.1/subject
-   *   y=http://www.w3.org/2000/01/rdf-schema#label
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect7() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 7");
-
-    // create the statement
-    String statement =
-        "select $x $y from <" + dcSchemaURI +
-        "> where (($x $y 'Subject') and ($x <" + rdfSchemaNamespace +
-        "label> 'Subject'))" +
-        "or <http://purl.org/dc/elements/1.1/subject> $y 'Subject' ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = interpreter.getLastAnswer();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x",
-                  new URIReferenceImpl(new URI(
-        "http://purl.org/dc/elements/1.1/subject")));
-    row.setObject("y",
-                  new URIReferenceImpl(new URI(
-        "http://www.w3.org/2000/01/rdf-schema#label")));
-
-    Answer expected = new AnswerImpl(trs);
-/*
-    expected.beforeFirst();
-    results.beforeFirst();
-    while (true) {
-      boolean expN = expected.next();
-      boolean resN = results.next();
-      if (expN && resN) {
-        log.warn("exp x = " + expected.getObject("x") + " exp y = " + expected.getObject("y") +
-            " res x = " + results.getObject("x") + " res y = " + results.getObject("y"));
-      } else if (!expN && !resN) {
-        log.warn("Finished dumping results");
-        break;
-      } else if (resN) {
-        do {
-          log.warn("extra result: res x = " + results.getObject("x") + " res y = " + results.getObject("y"));
-        } while (results.next());
-      } else {
-        log.warn("expN = " + expN + " resN = " + resN);
-        break;
-      }
-    }
-*/
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 7");
-  }
-
-  // testSelect7()
-
-  /**
-   * Test the interpreter using a select statement with a count and a having.
-   * Executes the following query: <pre>
-   * select count (
-   *   select $x $y
-   *   from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt;
-   *   where (($x $y 'Subject') and ($x &lt;http://www.w3.org/2000/01/rdf-schema#label&gt; 'Subject'))
-   * from &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt;
-   * where (($x $y 'Subject') and ($x &lt;http://www.w3.org/2000/01/rdf-schema#label&gt; 'Subject')) ;
-   * </pre> Expects results: <pre>
-   *   k0=http://purl.org/dc/elements/1.1/subject
-   *   y=http://www.w3.org/2000/01/rdf-schema#label
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSelect8() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting select test 8");
-
-    // create the statement
-    String statement =
-        "select $x $y count ( " +
-        "  select $x $y " +
-        "  from <" + dcSchemaURI + "> " +
-        "  where (($x $y 'Subject') " +
-        "  and ($x <" + rdfSchemaNamespace + "label> 'Subject'))) " +
-        "from <" + dcSchemaURI + "> " +
-        "where (($x $y 'Subject') " +
-        "and ($x <" + rdfSchemaNamespace + "label> 'Subject')) " +
-        "having $k0 <http://mulgara.org/mulgara#occurs> '1.0'^^<http://www.w3.org/2001/XMLSchema#double> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    Answer results = new AnswerImpl(interpreter.getLastAnswer());
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose the expected result
-    TestResultSet trs = new TestResultSet(new String[] {"x", "y", "k0"});
-    ResultSetRow row = new ResultSetRow(trs);
-    trs.addRow(row);
-    row.setObject("x", new URIReferenceImpl(
-        new URI("http://purl.org/dc/elements/1.1/subject")));
-    row.setObject("y", new URIReferenceImpl(
-        new URI("http://www.w3.org/2000/01/rdf-schema#label")));
-    row.setObject("k0", new LiteralImpl(1.0d));
-
-    Answer expected = new AnswerImpl(trs);
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    results.close();
-    expected.close();
-
-    // log that we've completed the test
-    log.info("Completed select test 7");
-  }
-
-  // testSelect8()
-
-  /**
-   * Test the interpreter using a delete statement. Executes the following query:
-   * <pre>
-   *   delete $s $p $o from &lt;rmi://localhost/database#model&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testDelete1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting delete test 1");
-
-    String statement;
-
-    // create the statement
-    statement = "delete $s $p $o from <file://foo/bar.txt> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    String expected = "Could not delete statements from file://foo/bar.txt" +
-        eol + "Predicate must be a valid URI";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed drop test 1");
-  }
-
-  /**
-   * Test the interpreter using a delete statement. Executes the following query:
-   * <pre>
-   *   delete $s <urn:foo:bar> $o from &lt;rmi://localhost/database#model&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testDelete2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting delete test 2");
-
-    String statement;
-
-    // create the statement
-    statement = "delete $s <urn:foo:bar> $o from <file://foo/bar.txt> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    String expected = "Could not delete statements from file://foo/bar.txt" +
-       eol + "Cannot use variables when deleting statements";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed drop test 2");
-  }
-
-  /**
-   * Test the interpreter using a directory statement. Executes the following
-   * query: <pre>
-   *   directory &lt;beep://rns.site1.net:7000/models&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testDirectory1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting directory DB test 1");
-
-    // create the statement
-    String statement = "directory <beep://rns.site1.net:7000/models> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed directory test 1");
-  }
-
-  // testDirectory1()
-
-  /**
-   * Test the interpreter using a create statement. Executes the following
-   * query: <pre>
-   *   create &lt;mulgara://localhost/database&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testCreate1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting create test 1");
-
-    // create the statement
-    String statement = "create <mulgara://localhost/database> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed create test 1");
-  }
-
-  // testCreate1()
-
-  /**
-   * Test the interpreter using a create statement. Executes the following
-   * query: <pre>
-   *   create &lt;mulgara://localhost/database#model&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testCreate2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting create test 2");
-
-    // create the statement
-    String statement = "create <mulgara://localhost/database#model> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed create test 2");
-  }
-
-  // testCreate2()
-
-  /**
-   * Test the interpreter using a drop statement. Executes the following query:
-   * <pre>
-   *   drop &lt;mulgara://localhost/database#model&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testDrop1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting drop test 1");
-
-    // create the statement
-    String statement = "drop <mulgara://localhost/database> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed drop test 1");
-  }
-
-  // testDrop1()
-
-  /**
-   * Test the interpreter using a drop statement. Executes the following query:
-   * <pre>
-   *   drop &lt;mulgara://localhost/database#model&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testDrop2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting drop test 2");
-
-    // create the statement
-    String statement = "drop <mulgara://localhost/database#model> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed drop test 2");
-  }
-
-  // testDrop2()
-  // Proposed tests
-  //
-  //insert unbraced triple into database
-  //insert unbraced triple into model
-  //insert braced triple into database
-  //insert braced triple into model
-  //insert unbraced database into database
-  //insert unbraced database into model
-  //insert unbraced model into database
-  //insert unbraced model into model
-  //insert braced database into database
-  //insert braced database into model
-  //insert braced model into database
-  //insert braced model into model
-  //insert unbraced select into database
-  //insert unbraced select into model
-  //insert braced select into database
-  //insert braced select into model
-  // insert 'title' 'title' 'title' into rmi://localhost/server1#insert ;
-  // -> this is a bad triple as it contains a literal as it's subject and predicate
-  //
-  // alias http://www.w3.org/2000/01/rdf-schema# as rdfs ;
-  // insert http://purl.org/dc/elements/1.1/language rdfs:label 'Language' into rmi://localhost/server1#insert ;
-  //
-  // or equivalently
-  //
-  // insert http://purl.org/dc/elements/1.1/language http://www.w3.org/2000/01/rdf-schema#label 'Language' into rmi://localhost/server1#insert ;
-  //
-  // iTQL> create rmi://localhost/server1#foo ;
-  // Successfully created model rmi://localhost/server1#foo
-  // iTQL> select $x $y $z from rmi://localhost/server1#foo where $x $y $x ;
-  // 2 columns: x y (0 rows)
-  // iTQL> insert http://purl.org/dc/elements/1.1/title http://www.w3.org/2000/01/rdf-schema#label 'Title' into rmi://localhost/server1#foo ;
-  // Successfully inserted statements into rmi://localhost/server1#foo
-  // iTQL> select $x $y $z from rmi://localhost/server1#foo where $x $y $x ;
-  // 2 columns: x y (1 rows)
-  //         x="Title"       y=http://www.w3.org/2000/01/rdf-schema#label
-  // iTQL> drop rmi://localhost/server1#foo ;
-  // Successfully dropped model rmi://localhost/server1#foo
-  // Proposed tests
-  //
-  //delete unbraced triple into database
-  //delete unbraced triple into model
-  //delete braced triple into database
-  //delete braced triple into model
-  //delete unbraced database into database
-  //delete unbraced database into model
-  //delete unbraced model into database
-  //delete unbraced model into model
-  //delete braced database into database
-  //delete braced database into model
-  //delete braced model into database
-  //delete braced model into model
-  //delete unbraced select into database
-  //delete unbraced select into model
-  //delete braced select into database
-  //delete braced select into model
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load &lt;http://purl.org/dc/elements/1.1&gt; into
-   *       &lt;mulgara://localhost/database#model&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 1");
-
-    // create the statement
-    String statement =
-        "load <http://purl.org/dc/elements/1.1> into <" + testModel + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 1");
-  }
-
-  // testLoad1()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; into
-   * &lt;mulgara://localhost/database&gt; ; </pre> Expects results:
-   * ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 2");
-
-    // create the statement
-    String statement =
-        "load <" + dcSchemaURI + "> into <" + server + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 2");
-  }
-
-  // testLoad2()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; into
-   * &lt;mulgara://localhost/database#model&gt; ; </pre> Expects results:
-   * ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad3() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 3");
-
-    // create the statement
-    String statement = "load <" + dcSchemaURI + "> into <" + testModel + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 3");
-  }
-
-  // testLoad3()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load as rdf &lt;http://<it>dchost</it> /<it>path</it> /dc.rdfs&gt; into
-   * &lt;mulgara://localhost/database#model&gt; ; </pre> Expects results:
-   * ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad4() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 4");
-
-    // create the statement
-    String statement =
-        "load <http://purl.org/dc/elements/1.1> into <" + testModel + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 4");
-  }
-
-  // testLoad4()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load as rdf &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; into
-   * &lt;mulgara://localhost/database&gt; ; </pre> Expects results:
-   * ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad5() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 5");
-
-    // create the statement
-    String statement =
-        "load <" + dcSchemaURI + "> into <" + server + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 5");
-  }
-
-  // testLoad5()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load as rdf &lt;file:<it>mulgarahome</it> /data/dc.rdfs&gt; into
-   * &lt;mulgara://localhost/database#model&gt; ; </pre> Expects results:
-   * ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad6() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 6");
-
-    // create the statement
-    String statement =
-        "load <" + dcSchemaURI + "> into <" + testModel + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 6");
-  }
-
-  // testLoad6()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load as serial &lt;http://<it>dchost</it> /<it>path</it> /<it>database
-   * </it>&gt; into &lt;mulgara://localhost/database#model&gt; ; </pre> Expects
-   * results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad7() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 7");
-
-    // create the statement
-    String statement =
-        "load <http://purl.org/dc/elements/1.1> into <" + testModel +
-        "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 7");
-  }
-
-  // testLoad7()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load as serial &lt;file:<it>mulgarahome</it> /data/<it>database</it> &gt;
-   * into &lt;mulgara://localhost/database&gt; ; </pre> Expects results:
-   * ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad8() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 8");
-
-    // create the statement
-    String statement =
-        "load <" + dcSchemaURI + "> into <" + server + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 8");
-  }
-
-  // testLoad8()
-
-  /**
-   * Test the interpreter using a load statement. Executes the following query:
-   * <pre>
-   *   load as serial &lt;file:<it>mulgarahome</it> /<it>database</it> &gt; into
-   * &lt;mulgara://localhost/database#model&gt; ; </pre> Expects results:
-   * ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoad9() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load test 9");
-
-    // create the statement
-    String statement =
-        "load <" + dcSchemaURI + "> into <" + testModel + "> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed load test 9");
-  }
-
-  // testLoad9()
-  // Proposed tests
-  //
-  //dump unbraced triple into file:<filename>
-  //dump braced triple into file:<filename>
-  //dump unbraced database into file:<filename>
-  //dump unbraced model into file:<filename>
-  //dump braced database into file:<filename>
-  //dump braced model into file:<filename>
-  //dump unbraced select into file:<filename>
-  //dump braced select into file:<filename>
-  //dump unbraced triple into file:<filename> as rdf
-  //dump braced triple into file:<filename> as rdf
-  //dump unbraced database into file:<filename> as rdf
-  //dump unbraced model into file:<filename> as rdf
-  //dump braced database into file:<filename> as rdf
-  //dump braced model into file:<filename> as rdf
-  //dump unbraced select into file:<filename> as rdf
-  //dump braced select into file:<filename> as rdf
-  //dump unbraced triple into file:<filename> as serial
-  //dump braced triple into file:<filename> as serial
-  //dump unbraced database into file:<filename> as serial
-  //dump unbraced model into file:<filename> as serial
-  //dump braced database into file:<filename> as serial
-  //dump braced model into file:<filename> as serial
-  //dump unbraced select into file:<filename> as serial
-  //dump braced select into file:<filename> as serial
-
-  /**
-   * Test the interpreter using a set statement. Executes the following query:
-   * <pre>
-   *   set time on ;
-   * </pre> Expects results: <pre>
-   *   Command timing on
-   *   Command execution time - XXX.XXX seconds
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSet1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting set test 1");
-
-    // create the statement
-    String statement = "set time on ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    String results;
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose expected result
-    String expected = "Command timing is on" + eol + "Command execution time - ";
-
-    // check that the result are what we expected (we cannot know the
-    // execution time)
-    assertEquals(true, results.startsWith(expected));
-
-    // log that we've completed the test
-    log.info("Completed set test 1");
-  }
-
-  // testSet1()
-
-  /**
-   * Test the interpreter using a set statement. Executes the following query:
-   * <pre>
-   *   set time off ;
-   * </pre> Expects results: <pre>
-   *   Command timing off
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testSet2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting set test 2");
-
-    // create the statement
-    String statement = "set time off ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    String results;
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // compose expected result
-    String expected = "Command timing is off";
-
-    // check that the result are what we expected
-    assertEquals(expected, results);
-
-    // log that we've completed the test
-    log.info("Completed set test 2");
-  }
-
-  // testSet2()
-
-  /**
-   * Test the interpreter using a backup statement. Executes the following
-   * query: <pre>
-   *    backup <rmi://localhost/server1> to <file:/tmp/foobackup1.gz> ;
-   * </pre> Expects results: <pre>
-   *    TODO
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testBackup1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting backup test 1");
-
-    // create the statement
-    File backupFile = new File(tmpDirectory, "server1backup.gz");
-    String statement =
-        "backup <"+server+"> to <" + backupFile.toURI() + ">;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    String results;
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log that we've completed the test
-    log.info("Completed backup test 1");
-  }
-
-  // testBackup1()
-
-  /**
-   * Test the interpreter using a restore statement. Executes the following
-   * query: <pre>
-   *    restore <rmi://localhost/server1> from <file:/tmp/foobackup1.gz> ;
-   * </pre> Expects results: <pre>
-   *    TODO
-   * </pre>
-   *
-   * @throws Exception if the test fails
-   */
-  public void testRestore1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting restore test 1");
-
-    // create the statement
-    File backupFile = new File(tmpDirectory, "server1backup.gz");
-    String statement =
-        "restore <"+server+"> from <" + backupFile.toURI() + ">;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    String results;
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log that we've completed the test
-    log.info("Completed restore test 1");
-  }
-
-  // testRestore1()
-
-  /**
-   * Tests the backup and restore functionality of Mulgara by running a query,
-   * backing up the DB, deleting the server.
-   *
-   * @throws Exception if the test fails
-   */
-  public void testBackupRestore1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting combined backup-restore test 1");
-
-    // TODO - perform the backup
-    // create the statement
-    File backupFile = new File(tmpDirectory, "server1backup.gz");
-    String statement =
-        "restore <"+server+"> from <" + backupFile.toURI() + ">;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    String results;
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log that we've completed the test
-    log.info("Completed combined backup-restore test 1");
-  }
-
-  // testBackupRestore1()
-
-  /**
-   * Tests the backup and restore functionality of Mulgara by running a query,
-   * backing up the DB, deleting the server.
-   *
-   * @throws Exception if the test fails
-   */
-  public void testBackupRestore2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting combined backup-restore test 2");
-
-    // TODO - perform the backup
-    // create the statement
-    File backupFile = new File(tmpDirectory, "server1backup.gz");
-    String statement =
-        "restore <"+server+"> from local <" + backupFile.toURI() + ">;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    String results;
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log that we've completed the test
-    log.info("Completed combined backup-restore test 2");
-  }
-
-  /**
-   * Tests the backup and restore functionality of Mulgara by running a query,
-   * backing up the DB, deleting the server.
-   *
-   * @throws Exception if the test fails
-   */
-  public void testBackupRestore3() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting combined backup-restore test 3");
-
-    // TODO - perform the backup
-    // create the statement
-    File backupFile = new File(tmpDirectory, "server1backup.gz");
-    String statement =
-        "restore <"+server+"> from remote <" + backupFile.toURI() + ">;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    // execute the query
-    String results;
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log that we've completed the test
-    log.info("Completed combined backup-restore test 3");
-  }
-
-
-
-  /**
-   * Test #1 for {@link ItqlInterpreter#parseQuery}.
-   *
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void test1ParseQuery() throws Exception {
-
-    log.info("Starting parse query 1");
-
-    // Compose the expected result
-    Query expected = new Query(
-        Arrays.asList(new Variable[] {
-        new Variable("x")}),                   // variable list
-        new ModelResource(new URI("x:m")),     // model expression
-        new ConstraintImpl(new Variable("x"),  // constraint expression
-        new URIReferenceImpl(new URI("x:p")),
-        new LiteralImpl("o")),
-        null,                                  // no having
-        Collections.EMPTY_LIST,                // no ordering
-        null,                                  // no limit
-        0,                                     // zero offset
-        new UnconstrainedAnswer());
-
-    // Check that the result is as expected
-    assertEquals(expected,
-                 interpreter.parseQuery(
-        "select $x from <x:m> where $x <x:p> 'o';"));
-
-    log.info("Completed parse query 1");
-  }
-
-  /**
-   * Test #2 for {@link ItqlInterpreter#parseQuery}. Non-queries should return a
-   * {@link ParserException}.
-   *
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void test2ParseQuery() throws Exception {
-
-    log.info("Starting parse query 2");
-
-    try {
-
-      String notAQuery = "quit";
-      Query query = interpreter.parseQuery(notAQuery);
-      fail("\"" + notAQuery + "\" erroneously parsed as \"" + query + "\"");
-    }
-    catch (ParserException e) {
-
-      // this is the correct response
-    }
-    log.info("Completed parse query 2");
-  }
-
-  /**
-   * Test #3 for {@link ItqlInterpreter#parseQuery}. This tests that the limit
-   * and offset can be assigned.
-   *
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void test3ParseQuery() throws Exception {
-
-    log.info("Starting parse query 3");
-    // Compose the expected result
-    Query expected = new Query(
-        Arrays.asList(new Variable[] {
-        new Variable("x")}),                   // variable list
-        new ModelResource(new URI("x:m")),     // model expression
-        new ConstraintImpl(new Variable("x"),  // constraint expression
-        new URIReferenceImpl(new URI("x:p")),
-        new LiteralImpl("o")),
-        null,                                  // no having
-        Collections.EMPTY_LIST,                // no ordering
-        new Integer(10),                       // limit
-        2,                                     // offset
-        new UnconstrainedAnswer());
-
-    // Check that the result is as expected
-    assertEquals(expected,
-                 interpreter.parseQuery(
-        "select $x from <x:m> where $x <x:p> 'o' limit 10 offset 2;"));
-    log.info("Completed parse query 3");
-  }
-
-  /**
-   * Test #3 for {@link ItqlInterpreter#parseQuery}. This tests the having
-   * expression.
-   *
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void test4ParseQuery() throws Exception {
-
-    log.info("Starting parse query 4");
-    // Compose the expected result
-
-    List varList = Arrays.asList(new Variable[] { new Variable("x") });
-    ModelExpression model = new ModelResource(new URI("x:m"));
-    ConstraintExpression where =  new ConstraintImpl(
-        new Variable("x"),
-        new URIReferenceImpl(new URI("x:p")),
-        new LiteralImpl("o"));
-    ConstraintHaving having = new ConstraintOccurs(new Variable("x"),
-        new LiteralImpl(2d));
-
-    Query expected = new Query(
-        varList,                               // variable list
-        model,                                 // model expression
-        where,                                 // constraint expression
-        having,                                // a simple having
-        Collections.EMPTY_LIST,                // no ordering
-        new Integer(10),                       // limit
-        2,                                     // offset
-        new UnconstrainedAnswer());
-
-    // Check that the result is as expected
-    assertEquals(expected, interpreter.parseQuery("select $x from <x:m> " +
-        "where $x <x:p> 'o' " +
-        "having $x <http://mulgara.org/mulgara#occurs> " +
-        "'2.0'^^<http://www.w3.org/2001/XMLSchema#double> limit 10 offset 2;"));
-    log.info("Completed parse query 4");
-  }
-
-  // ItqlInterpreterUnitTest()
-  //
-  // Test configuration
-  //
-
-  /**
-   * Initialise members.
-   *
-   * @throws Exception if something goes wrong
-   */
-  protected void setUp() throws Exception {
-
-    // initialise the interpreter if needed
-    if (this.interpreter == null) {
-
-      /*
-      SessionFactory sessionFactory =
-        SessionFactoryFinder.newSessionFactory(null);
-      */
-
-      this.interpreter = new ItqlInterpreter(
-        /*
-        sessionFactory.newSession(),
-        sessionFactory.getSecurityDomain(),
-        */
-        new HashMap()
-      );
-    }
-
-    // end if
-    // initialise the dublin core schema test data if needed
-    if (dcSchemaURI == null) {
-
-      dcSchemaURI =
-          new URI(new File(System.getProperty("cvs.root") + "/data/dc.rdfs").
-                  toURL()
-                  .toString());
-    }
-
-    // end if
-    // initialise the test model if needed
-    if (testModel == null) {
-
-      testModel = server+"#itqlmodel2";
-    }
-
-    // end if
-  }
-
-  /**
-   * Test the interpreter using a create statement. Executes the following
-   * query: <pre>
-   *   create &lt;mulgara://localhost/database&gt; ;
-   * </pre> Expects results: ParserException
-   *
-   * @throws Exception if the test fails
-   */
-  public void testCreate3() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting create test 3");
-
-    // create the statement
-    String statement = "create <"+ testModel +"> ;";
-
-    // log the query we'll be sending
-    log.debug("Executing statement : " + statement);
-
-    String results = "";
-
-    // execute the query
-    interpreter.executeCommand(statement);
-    results = interpreter.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.info("Completed create test 3");
-  }
-
-  // testCreate1()
-
-
-  /**
-   * Test the interpreter using a load API remotely .
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi1() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load API test 1");
-
-    URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
-    URI modelURI = new URI(testModel);
-
-    // execute the load remotely
-    long statements = interpreter.load(null, sourceURI, modelURI);
-
-    this.assertEquals("Incorrect number of statements inserted", 146, statements);
-    log.info("Completed test load api 1");
-  }
-
-  // testLoadApi1()
-
-  /**
-   * Test the interpreter using a load API locally
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi2() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load API test 2");
-
-    URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
-    URI modelURI = new URI(testModel);
-
-    // open and wrap the inputstream
-    RemoteInputStreamSrvImpl srv =
-        new RemoteInputStreamSrvImpl(sourceURI.toURL().openStream());
-
-    // prepare it for exporting
-    UnicastRemoteObject.exportObject(srv);
-
-    RemoteInputStream inputStream = new RemoteInputStream(srv);
-
-    // execute the load locally
-    long statements = interpreter.load(inputStream,
-                                       sourceURI, modelURI);
-
-    this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
-    inputStream.close();
-
-    log.info("Completed test load api 2");
-  }
-
-  // testLoadApi2()
-
-  /**
-   * Test the interpreter using a load API locally
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi3() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load API test 3");
-
-    URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
-    URI dummyURI = new URI("http://mydummysite.com/rssfeed.rdf");
-    URI modelURI = new URI(testModel);
-
-    // execute the load locally - pass an invalid URI for the server.
-    // This should succeed as the server will ignore the dummyURI
-    long statements = interpreter.load(sourceURI.toURL().openStream(),
-                                       dummyURI, modelURI);
-
-    this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
-    log.info("Completed test load api 3");
-  }
-
-  /**
-   * Test the interpreter using a load API locally
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi4() throws Exception {
-
-    // log that we're executing the test
-    log.info("Starting load API test 4");
-
-    URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
-    URI modelURI = new URI(testModel);
-
-    // execute the load locally
-    long statements = interpreter.load(sourceURI.toURL().openStream(),
-                                       modelURI);
-
-    this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
-    log.info("Completed test load api 4");
-  }
-
-  /**
-    * Test the interpreter using a backup API remotely .
-    *
-    * @throws Exception if the test fails
-    */
-   public void testBackupApi1() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting backup API test 1");
-
-     File file = new File(tmpDirectory, "backup1.rdf");
-     file.delete();
-
-     URI modelURI = new URI(testModel);
-
-     // execute the backup remotely
-     interpreter.backup(modelURI, file);
-
-     this.assertTrue("Expected a backup file", file.exists());
-   }
-
-   // testbackupApi1()
-
-   /**
-    * Test the interpreter using a backup API locally
-    *
-    * @throws Exception if the test fails
-    */
-   public void testBackupApi2() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting backup API test 2");
-
-     File file = new File(tmpDirectory, "backup2.rdf");
-     file.delete();
-
-     URI modelURI = new URI(testModel);
-
-     // execute the backup remotely
-     interpreter.backup(modelURI, new FileOutputStream(file));
-
-     this.assertTrue("Expected a backup file", file.exists());
-
-   }
-
-   // testbackupApi2()
-
-   /**
-    * Test the interpreter using a backup API locally
-    *
-    * @throws Exception if the test fails
-    */
-   public void testBackupApi3() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting backup API test 3");
-
-     File file = new File(tmpDirectory, "backup1.gz");
-     file.delete();
-
-     URI serverURI = new URI(server);
-
-     // execute the backup locally
-     interpreter.backup(serverURI, file);
-
-     this.assertTrue("Expected a backup file", file.exists());
-
-   }
-
-   /**
-    * Test the interpreter using a backup API locally
-    *
-    * @throws Exception if the test fails
-    */
-   public void testBackupApi4() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting backup API test 3");
-
-     File file = new File(tmpDirectory, "backup2.gz");
-     file.delete();
-
-     URI serverURI = new URI(server);
-
-     // execute the backup remotely
-     interpreter.backup(serverURI, new FileOutputStream(file));
-
-     this.assertTrue("Expected a backup file", file.exists());
-
-   }
-
-   /**
-    * Test the interpreter using a Load API locally
-    *
-    * @throws Exception if the test fails
-    */
-   public void testLoadBackupApi1() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting load a backup API test 1");
-
-     File file = new File(tmpDirectory, "backup1.rdf");
-
-     URI modelURI = new URI(testModel);
-
-     // execute the backup remotely
-     long statements = interpreter.load(file.toURL().openStream(), modelURI);
-
-     this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
-   }
-
-
-   /**
-    * Test the interpreter using a restore API locally
-    *
-    * @throws Exception if the test fails
-    */
-   public void testRestoreApi1() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting Restore API test 1");
-
-     File file = new File(tmpDirectory, "backup1.gz");
-
-     URI serverURI = new URI(server);
-
-     // execute the backup remotely
-     interpreter.restore(new FileInputStream(file), serverURI);
-
-   }
-
-   /**
-    * Test the interpreter using a restore API remotely
-    *
-    * @throws Exception if the test fails
-    */
-   public void testRestoreApi2() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting Restore API test 2");
-
-     File file = new File(tmpDirectory, "backup1.gz");
-
-     URI serverURI = new URI(server);
-
-     // execute the backup remotely
-     interpreter.restore(null, serverURI, file.toURI());
-
-   }
-
-   /**
-    * Test the interpreter using a restore API locally
-    *
-    * @throws Exception if the test fails
-    */
-   public void testRestoreApi3() throws Exception {
-
-     // log that we're executing the test
-     log.info("Starting Restore API test 3");
-
-     File file = new File(tmpDirectory, "backup2.gz");
-
-     // provide a not existence file.
-     // this should not fail as the input stream is used
-     File dummy = new File(tmpDirectory, "dummyfile.gz");
-
-     URI serverURI = new URI(server);
-
-     // execute the backup remotely
-     interpreter.restore(file.toURL().openStream(), serverURI, dummy.toURI());
-
-   }
-
-
-  // main()
-}

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlUtil.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/ItqlUtil.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlUtil.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ItqlUtil.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,71 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.itql;
+
+/**
+ * A set of utilities to provide legacy support for ItqlInterpreter operations.
+ * @created Oct 11, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+class ItqlUtil {
+
+  /** System line separator character */
+  private static final String EOL = System.getProperty("line.separator");
+
+  /**
+   * Pretty prints the Exception Chain.
+   *
+   * @param e the throwable exception
+   * @param preferredDepth the preferred depth to go into the exception to
+   *   retrieve the root cause.  A depth of zero will chain all exceptions
+   *   together.
+   * @return A string containing the pretty printed Exception Chain.
+   */
+  public static String getCause(Throwable e, int preferredDepth) {
+
+    // Keep getting the cause of the message until we reach preferred depth or null cause.
+    Throwable preferredException = e;
+    int index = 0;
+    while ((preferredException != null) && (index != preferredDepth)) {
+      // Pre-check next exception and increment index if it's not null.
+      if (preferredException.getCause() != null) index++;
+      // Get next exception in the chain
+      preferredException = preferredException.getCause();
+    }
+
+    // Update e to the preferred exception if it is not null
+    if (preferredException != null) e = preferredException;
+
+    String message = e.getMessage();
+    if (message == null) message = "";
+
+    // get the cause of the exception
+    Throwable cause = e.getCause();
+
+    // descend into exception if possible
+    if (cause != null) {
+      // pretty print the cause
+      String causeMsg = getCause(cause, 0);
+      // only add the cause's message if there was one
+      if (causeMsg != null) {
+        // Extract the class name from the full path
+        String exceptionClassName = cause.getClass().getName();
+        exceptionClassName = exceptionClassName.substring(exceptionClassName.lastIndexOf('.') + 1);
+        message += (EOL + "Caused by: (" + exceptionClassName + ") " + causeMsg);
+      }
+    }
+    return message;
+  }
+
+}

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ModelExpressionBuilder.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ModelExpressionBuilder.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/ModelExpressionBuilder.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -94,6 +94,8 @@
    * org.mulgara.itql.node.PModelExpression}, using an <code>aliasMap</code>
    * to resolve aliases.
    *
+   * TODO: aliasMap is currently ignored!
+   * 
    * @param aliasMap the map from targets to aliases
    * @param expression a model expression from the parser
    * @return RETURNED VALUE TO DO
@@ -103,7 +105,7 @@
    *      a resource whose text violates <a
    *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
    */
-  public static ModelExpression build(Map aliasMap,
+  public static ModelExpression build(Map<String,URI> aliasMap,
     PModelExpression expression) throws QueryException, URISyntaxException {
 
     // validate aliasMap parameter
@@ -126,7 +128,7 @@
     }
 
     // build the model expression from the parser input
-    ModelExpression modelExpression = buildModelExpression(expression);
+    ModelExpression modelExpression = buildModelExpression(expression, aliasMap);
 
     // logger that we've building successfully built a model expression
     if (logger.isDebugEnabled()) {
@@ -156,7 +158,7 @@
    *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
    */
   private static ModelExpression buildModelExpression(
-    PModelExpression rawModelExpression)
+    PModelExpression rawModelExpression, Map<String,URI> aliasMap)
     throws QueryException, URISyntaxException {
 
     // validate the rawModelExpression parameter
@@ -198,8 +200,8 @@
       }
 
       // get the LHS and RHS operands of the union
-      ModelExpression lhs = buildModelExpression(orModelExpression);
-      ModelExpression rhs = buildModelExpression(modelTerm);
+      ModelExpression lhs = buildModelExpression(orModelExpression, aliasMap);
+      ModelExpression rhs = buildModelExpression(modelTerm, aliasMap);
 
       // logger that we've resolved the operands
       if (logger.isDebugEnabled()) {
@@ -209,8 +211,7 @@
 
       // apply the union
       modelExpression = new ModelUnion(lhs, rhs);
-    }
-    else if (rawModelExpression instanceof ATermModelExpression) {
+    } else if (rawModelExpression instanceof ATermModelExpression) {
 
       // logger that we've got a term model expression
       if (logger.isDebugEnabled()) {
@@ -218,8 +219,7 @@
       }
 
       // get the model term
-      PModelTerm modelTerm =
-        ((ATermModelExpression) rawModelExpression).getModelTerm();
+      PModelTerm modelTerm = ((ATermModelExpression)rawModelExpression).getModelTerm();
 
       // logger that we're about to resolve the term into an expression
       if (logger.isDebugEnabled()) {
@@ -227,7 +227,7 @@
       }
 
       // drill down into the model term
-      modelExpression = buildModelExpression(modelTerm);
+      modelExpression = buildModelExpression(modelTerm, aliasMap);
     }
 
     // end if
@@ -263,8 +263,9 @@
    *      a resource whose text violates <a
    *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
    */
-  private static ModelExpression buildModelExpression(PModelTerm rawModelTerm)
-    throws QueryException, URISyntaxException {
+  private static ModelExpression buildModelExpression(
+      PModelTerm rawModelTerm, Map<String,URI> aliasMap
+    ) throws QueryException, URISyntaxException {
 
     // validate the rawModelTerm parameter
     if (rawModelTerm == null) {
@@ -299,20 +300,20 @@
       }
 
       // drill down into the model part
-      modelExpression = buildModelExpression(modelPart);
-    }
-    else if (rawModelTerm instanceof AAndModelTerm) {
+      modelExpression = buildModelExpression(modelPart, aliasMap);
 
+    } else if (rawModelTerm instanceof AAndModelTerm) {
+
       // logger that we've got a AND model term
       if (logger.isDebugEnabled()) {
         logger.debug("Found AND contraint term " + rawModelTerm);
       }
 
       // get the model term
-      PModelTerm modelTerm = ((AAndModelTerm) rawModelTerm).getModelTerm();
+      PModelTerm modelTerm = ((AAndModelTerm)rawModelTerm).getModelTerm();
 
       // get the model part
-      PModelPart modelPart = ((AAndModelTerm) rawModelTerm).getModelPart();
+      PModelPart modelPart = ((AAndModelTerm)rawModelTerm).getModelPart();
 
       // logger that we've found the operands of the union
       if (logger.isDebugEnabled()) {
@@ -321,8 +322,8 @@
       }
 
       // get the LHS and RHS operands of the intersection
-      ModelExpression lhs = buildModelExpression(modelTerm);
-      ModelExpression rhs = buildModelExpression(modelPart);
+      ModelExpression lhs = buildModelExpression(modelTerm, aliasMap);
+      ModelExpression rhs = buildModelExpression(modelPart, aliasMap);
 
       // logger that we've resolved the operands
       if (logger.isDebugEnabled()) {
@@ -338,8 +339,7 @@
     // we should not be returning null
     if (modelExpression == null) {
 
-      throw new QueryException("Unable to parse ITQL model term " +
-        "into a valid model expression");
+      throw new QueryException("Unable to parse ITQL model term into a valid model expression");
     }
 
     // end if
@@ -367,8 +367,9 @@
    *      a resource whose text violates <a
    *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
    */
-  private static ModelExpression buildModelExpression(PModelPart rawModelPart)
-    throws QueryException, URISyntaxException {
+  private static ModelExpression buildModelExpression(
+      PModelPart rawModelPart, Map<String,URI> aliasMap
+    ) throws QueryException, URISyntaxException {
 
     // validate the rawModelPart parameter
     if (rawModelPart == null) {
@@ -394,8 +395,7 @@
       }
 
       // get the model factor
-      PModelFactor modelFactor =
-        ((AFactorModelPart) rawModelPart).getModelFactor();
+      PModelFactor modelFactor = ((AFactorModelPart)rawModelPart).getModelFactor();
 
       // logger that we're recursing with a model factor
       if (logger.isDebugEnabled()) {
@@ -403,9 +403,8 @@
       }
 
       // drill down into the model part
-      modelExpression = buildModelExpression(modelFactor);
-    }
-    else if (rawModelPart instanceof AXorModelPart) {
+      modelExpression = buildModelExpression(modelFactor, aliasMap);
+    } else if (rawModelPart instanceof AXorModelPart) {
 
       // logger that we've got a AND model term
       if (logger.isDebugEnabled()) {
@@ -413,21 +412,19 @@
       }
 
       // get the model term
-      PModelPart modelPart = ((AXorModelPart) rawModelPart).getModelPart();
+      PModelPart modelPart = ((AXorModelPart)rawModelPart).getModelPart();
 
       // get the model factor
-      PModelFactor modelFactor =
-        ((AXorModelPart) rawModelPart).getModelFactor();
+      PModelFactor modelFactor = ((AXorModelPart)rawModelPart).getModelFactor();
 
       // logger that we've found the operands of the union
       if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with model part " + modelPart + " & model factor " +
-          modelFactor);
+        logger.debug("Recursing with model part " + modelPart + " & model factor " + modelFactor);
       }
 
       // get the LHS and RHS operands of the intersection
-      ModelExpression lhs = buildModelExpression(modelPart);
-      ModelExpression rhs = buildModelExpression(modelFactor);
+      ModelExpression lhs = buildModelExpression(modelPart, aliasMap);
+      ModelExpression rhs = buildModelExpression(modelFactor, aliasMap);
 
       // logger that we've resolved the operands
       if (logger.isDebugEnabled()) {
@@ -443,8 +440,7 @@
     // we should not be returning null
     if (modelExpression == null) {
 
-      throw new QueryException("Unable to parse ITQL model term " +
-        "into a valid model expression");
+      throw new QueryException("Unable to parse ITQL model term into a valid model expression");
     }
 
     // end if
@@ -473,13 +469,13 @@
    *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
    */
   private static ModelExpression buildModelExpression(
-    PModelFactor rawModelFactor) throws QueryException, URISyntaxException {
+        PModelFactor rawModelFactor, Map<String,URI> aliasMap
+      ) throws QueryException, URISyntaxException {
 
     // validate the rawModelFactor parameter
     if (rawModelFactor == null) {
 
-      throw new IllegalArgumentException("Null \"rawModelFactor\" " +
-        "parameter");
+      throw new IllegalArgumentException("Null \"rawModelFactor\" parameter");
     }
 
     // end if
@@ -500,8 +496,7 @@
       }
 
       // get the resource
-      String resource =
-        ((AResourceModelFactor) rawModelFactor).getResource().getText();
+      String resource = ((AResourceModelFactor)rawModelFactor).getResource().getText();
 
       // logger that we've found a resource
       if (logger.isDebugEnabled()) {
@@ -509,10 +504,9 @@
       }
 
       // this resource is what we're looking for
-      URI modelURI = new URI(resource);
+      URI modelURI = URIUtil.convertToURI(resource, aliasMap);
       modelExpression = new ModelResource(ServerURIHandler.removePort(modelURI));
-    }
-    else if (rawModelFactor instanceof AExpressionModelFactor) {
+    } else if (rawModelFactor instanceof AExpressionModelFactor) {
 
       // logger that we've got an expression model factor
       if (logger.isDebugEnabled()) {
@@ -520,8 +514,7 @@
       }
 
       // get the model expression
-      PModelExpression embeddedModelExpression =
-        ((AExpressionModelFactor) rawModelFactor).getModelExpression();
+      PModelExpression embeddedModelExpression = ((AExpressionModelFactor)rawModelFactor).getModelExpression();
 
       // logger that we're recursing with a model expression
       if (logger.isDebugEnabled()) {
@@ -529,7 +522,7 @@
       }
 
       // build the model expression
-      modelExpression = buildModelExpression(embeddedModelExpression);
+      modelExpression = buildModelExpression(embeddedModelExpression, aliasMap);
     }
 
     // end if

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/SableCCInterpreter.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/SableCCInterpreter.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/SableCCInterpreter.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/SableCCInterpreter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,85 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.itql;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.mulgara.itql.node.PLiteral;
+import org.mulgara.itql.node.TResource;
+import org.mulgara.itql.node.Token;
+import org.mulgara.parser.Interpreter;
+import org.mulgara.query.Query;
+import org.mulgara.query.QueryException;
+import org.mulgara.query.Variable;
+import org.mulgara.query.rdf.LiteralImpl;
+
+/**
+ * Interpreter methods specific to sableCC structures.
+ * 
+ * @created Aug 24, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public interface SableCCInterpreter extends Interpreter {
+
+  /**
+   * Construct a {@link LiteralImpl} from a {@link PLiteral}.
+   *
+   * @param p  the instance to convert
+   */
+  public LiteralImpl toLiteralImpl(PLiteral p);
+
+  /**
+   * Returns an anonymous variable unique for this interpreter.
+   * Note: We really should introduce a new subclass of Variable
+   * that is explicitly anonymous, but for now this will do.
+   */
+  public Variable nextAnonVariable();
+
+  /**
+   * Executes a query and returns its results.
+   *
+   * @param rawQuery a select query, represented as either a {@link
+   *      org.mulgara.itql.node.ASelectCommand} or a {@link
+   *      org.mulgara.itql.node.ASelectSetOfTriples}
+   * @return the answer to the query
+   * @throws QueryException if the query cannot be executed
+   * @throws URISyntaxException if the <code>query</code> contains a resource
+   *      whose text violates <a href="http://www.isi.edu/in-notes/rfc2396.txt">
+   *      RFC\uFFFD2396</a>
+   */
+  public Query buildQuery(org.mulgara.itql.node.Node rawQuery) throws QueryException,
+      URISyntaxException;
+
+  /**
+   * Convert SableCC-generated {@link TResource} tokens into {@link URI}s.
+   *
+   * Resolution will treat the token as an XML
+   * <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">qualified
+   * names</a> if the {@link #aliasMap} <code>aliasMap</code> contains a key
+   * for the URI scheme part that can be treated as an XML namespace prefix.
+   * For example, <kbd>dc:title</kbd> is treated as a qname and mapped to the
+   * to the URI <kbd>http://purl.org/dc/elements/1.1/title</kbd>, assuming the
+   * {@link #aliasMap} had an entry mapping <code>"dc"</code> to the Dublin
+   * Core namespace.
+   *
+   * @param token  the token to be converted, which should actually be a
+   *   {@link TResource}
+   * @throws Error if the <var>token</var> text isn't syntactically
+   *   a {@link URI}; this shouldn't ever occur, assuming the <var>token</var>
+   *   is a {@link TResource}
+   */
+  URI toURI(Token token);
+
+}

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlAutoInterpreter.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/TqlAutoInterpreter.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlAutoInterpreter.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlAutoInterpreter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,394 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.itql;
+
+import java.net.URI;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+import org.mulgara.connection.Connection;
+import org.mulgara.connection.ConnectionException;
+import org.mulgara.connection.ConnectionFactory;
+import org.mulgara.connection.DummyConnection;
+import org.mulgara.parser.Interpreter;
+import org.mulgara.query.Answer;
+import org.mulgara.query.QueryException;
+import org.mulgara.query.operation.Command;
+import org.mulgara.query.operation.Commit;
+import org.mulgara.query.operation.LocalCommand;
+import org.mulgara.query.operation.Rollback;
+import org.mulgara.query.operation.SetAutoCommit;
+import org.mulgara.query.operation.TxOp;
+import org.mulgara.server.Session;
+
+/**
+ * This class interprets TQL statements, and automatically executes them,
+ * establishing connections to servers when required.
+ * 
+ * @created Sep 11, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class TqlAutoInterpreter {
+  /** The logger. */
+  private final static Logger logger = Logger.getLogger(TqlAutoInterpreter.class.getName());
+
+  /** A connection for receiving state changes to the local machine. */
+  private static Connection localStateConnection = new DummyConnection();
+
+  /** The parser and AST builder for commands. */
+  private Interpreter interpreter = new TqlInterpreter();
+
+  /** A user readable message resulting from the most recent command. */
+  private String lastMessage;
+
+  /** The most answer returned from the most recent command, if it was a query. */
+  private Answer lastAnswer;
+
+  /** The most recent exception, if there was one. */
+  private Exception lastException;
+
+  /** Factory for building and caching connections. */
+  private ConnectionFactory connectionFactory = new ConnectionFactory();
+
+  /** Indicates that the client is in a transaction. */
+  private boolean inTransaction;
+
+  /** All the connections involved in the current transaction. */
+  private Collection<Connection> transConnections = new LinkedList<Connection>();
+  
+  /**
+   * Holds the client security domain. Need to connect this to URIs,
+   * but the old interfaces don't know how to do this.
+   * <em>Security is currently unimplemented.</em>
+   */
+  private URI securityDomain = null;
+
+  /**
+   * Creates a new autointerpreter with no prior connections.
+   */
+  public TqlAutoInterpreter() {
+    inTransaction = false;
+    resetState();
+  }
+  
+
+  /**
+   * Execute a query.  The results of the query will set the state of this object.
+   * @param command The string containing the query to execute.
+   * @return <code>false</code> if the command asks to exit, <code>true</code> to continue normal operation.
+   */
+  public boolean executeCommand(String command) {
+    resetState();
+
+    if (logger.isDebugEnabled()) logger.debug("Parsing the command: " + command);
+    Command cmd = null;
+    try {
+      cmd = interpreter.parseCommand(command);
+    } catch (Exception e) {
+      lastMessage = "Error parsing the query";
+      lastException = e;
+      return true;
+    }
+    if (cmd == null) {
+      lastMessage = "";
+      return true;
+    }
+
+    // execute the operation
+    try {
+      // set up a connection, if required
+      Connection conn = establishConnection(cmd);
+      handleResult(cmd.execute(conn), cmd);
+      updateConnectionsForTx(conn, cmd);
+      lastMessage = cmd.getResultMessage();
+    } catch (Exception e) {
+      lastException = e;
+      lastMessage = "Error: " + e.getMessage();
+    }
+
+    // test if the command wants the user to quit - return false if it does
+    return !(cmd.isLocalOperation() && ((LocalCommand)cmd).isQuitCommand());
+  }
+  
+  
+  /**
+   * Sets the security domain for the client.
+   * <em>Security is currently unimplemented.</em>
+   * @param domain The URI of the service which authenticates the client.
+   *               e.g. ldap://ldap.domain.net/o=mycompany
+   */
+  public void setSecurityDomain(URI domain) {
+    securityDomain = domain;
+  }
+
+  
+  /**
+   * Query for the currently used security domain.
+   * <em>Security is currently unimplemented.</em>
+   */
+  public URI getSecurityDomain() {
+    return securityDomain;
+  }
+
+
+  /** @return the message set from the last operation */
+  public String getLastMessage() { return lastMessage; }
+
+  /** @return the last answer returned from a query, or <code>null</code> if the last operation was not a query */
+  public Answer getLastAnswer() { return lastAnswer; }
+
+  /** @return the exception thrown from the last operation, or <code>null</code> if there was no error */
+  public Exception getLastException() { return lastException; }
+
+
+  /**
+   * Close any resources that are still in use, and rolls back any outstanding transactions.
+   */
+  public void close() {
+    if (inTransaction) {
+      logger.info("Closing a current transaction.  Rolling back.");
+      try {
+        handleTxOp(new SetAutoCommit(true));
+      } catch (QueryException e) {
+        logger.error("Error while cleaning up a transaction", e);
+      }
+    }
+    assert transConnections.isEmpty();
+    connectionFactory.closeAll();
+  }
+
+
+  /**
+   * Resets the internal state in preparation for a new operation to be executed.
+   */
+  private void resetState() {
+    lastMessage = null;
+    lastAnswer = null;
+    lastException = null;
+  }
+
+
+  /**
+   * Process the result from a command.
+   * @param result The result to handle.
+   * @param cmd The command that gave the result. Used for type checking.
+   */
+  private void handleResult(Object result, Command cmd) {
+    if (result != null) {
+      if (cmd.isAnswerable()) lastAnswer = (Answer)result;
+      else logger.debug("Result: " + result);
+    }
+  }
+
+
+  /**
+   * Returns a connection to a server for a given command.
+   * @param cmd The command to get a connection to execute on.
+   * @return A connection to the server, cached if available.
+   * @throws ConnectionException It was not possible to create a connection to the described server.
+   * @throws QueryException There is a transaction underway, but the new connection cannot turn off autocommit.
+   */
+  private Connection establishConnection(Command cmd) throws ConnectionException, QueryException {
+    URI serverUri = cmd.getServerURI();
+
+    // check for server operations where we don't know the server
+    if (serverUri == null && !cmd.isLocalOperation()) {
+      // no server URI, but not local. Get a connection for a null URI
+      // eg. select .... from <file:///...>
+      Connection connection = connectionFactory.newConnection(serverUri);
+      configureForTransaction(connection);
+      return connection;
+    }
+    
+    // go the normal route for getting a connection for a given server location
+    return establishConnection(serverUri);
+  }
+
+
+  /**
+   * Returns a connection to the server with the given URI.
+   * NB: Not for general use. Available to ItqlInterpreterBean only to support
+   * legacy requests to get a session.
+   * @param serverUri The URI for the server to get a connection to. <code>null</code> for
+   *        Local operations that do not require a server.
+   * @return A connection to the server, cached if available.
+   * @throws ConnectionException It was not possible to create a connection to the described server.
+   * @throws QueryException There is a transaction underway, but the new connection cannot turn off autocommit.
+   */
+  Connection establishConnection(URI serverUri) throws ConnectionException, QueryException {
+    // get a new connection, or use the local one for non-server operations
+    Connection connection = (serverUri == null) ? localStateConnection : connectionFactory.newConnection(serverUri);
+    // update the connection if it needs to enter a current transaction
+    configureForTransaction(connection);
+    return connection;
+  }
+
+
+  /**
+   * Set up the given connection for a current transaction, if one is active at the moment.
+   * @param connection The connection to configure. The dummy connection is not configured.
+   * @throws QueryException An error while setting up the connection for the transaction.
+   */
+  private void configureForTransaction(Connection connection) throws QueryException {
+    // If in a transaction, turn off autocommit - ignore the dummy connection
+    if (inTransaction && connection.getAutoCommit() && connection != localStateConnection) {
+      assert !(connection instanceof DummyConnection);
+      connection.setAutoCommit(false);
+      assert !transConnections.contains(connection);
+      transConnections.add(connection);
+    }
+  }
+
+
+  /**
+   * Returns the current alias map.  Needs to treat the internal interpreter
+   * explicitly as a TqlInterpreter.
+   * @deprecated Available to ItqlInterpreterBean only to support legacy requests.
+   * @return The mapping of namespaces to the URI for that space.
+   */
+  Map<String,URI> getAliasesInUse() {
+    return ((TqlInterpreter)interpreter).getAliasMap();
+  }
+  
+  
+  /**
+   * Sets the current alias map.  Needs to treat the internal interpreter
+   * explicitly as a TqlInterpreter.
+   * @deprecated Available to ItqlInterpreterBean only to support legacy requests.
+   */
+  void setAliasesInUse(Map<String,URI> map) {
+    ((TqlInterpreter)interpreter).setAliasMap(map);
+  }
+  
+  
+  /**
+   * Clears the last exception.
+   * @deprecated Available to ItqlInterpreterBean only to support legacy requests.
+   */
+  void clearLastException() {
+    lastException = null;
+  }
+
+
+  /**
+   * Returns the internal local connection.  Supports local operations for the current package.
+   * @return The local "state" connection.
+   */
+  Connection getLocalConnection() {
+    return localStateConnection;
+  }
+
+
+  /**
+   * Commits all connections that started on a transaction.  This operates directly
+   * on all known transacted connections.
+   * @throws QueryException One of the connections could not be successfully committed.
+   */
+  void commitAll() throws QueryException {
+    handleTxOp(new Commit());
+  }
+
+  /**
+   * Rolls back all connections that started on a transaction.  This oeprates directly
+   * on all known transacted connections.
+   * @throws QueryException One of the connections could not be successfully rolled back.
+   */
+  void rollbackAll() throws QueryException {
+    handleTxOp(new Rollback());
+  }
+
+
+  /**
+   * Seeds the cache with a connection wrapping the given session.
+   * @deprecated Only for use by {@link ItqlInterpreterBean}.
+   * @param session The session to seed into the connection cache.
+   */
+  void preSeedSession(Session session) {
+    // get back a new connection, and then drop it, since it will now be cached
+    try {
+      connectionFactory.newConnection(session);
+    } catch (ConnectionException e) {
+      logger.warn("Unable to use the given session for establishing a connection", e);
+    }
+  }
+
+
+  /**
+   * Perform any actions required on the update of the state of a connection.
+   * Most commands will skip through this method. Only transaction commands do anything.
+   * @param conn The connection whose state needs checking.
+   * @throws QueryException Can be caused by a failed change into a transaction.
+   */
+  void updateConnectionsForTx(Connection conn, Command cmd) throws QueryException {
+    // check if the transaction state changed on a setAutocommit operations, or if the command is a Tx operation
+    if (inTransaction == conn.getAutoCommit() || cmd.isTxCommitRollback()) {
+      // check that transaction changes came from setAutoCommit commands
+      assert inTransaction != conn.getAutoCommit() || cmd instanceof org.mulgara.query.operation.SetAutoCommit: "Got a state change on " + cmd.getClass() + " instead of SetAutoCommit";
+      // check that if we are starting a transaction then the transConnections list is empty
+      assert inTransaction != conn.getAutoCommit() || conn.getAutoCommit() || transConnections.isEmpty();
+      // save the number of active connections
+      int activeConnections = transConnections.size();
+      // handle the transaction operation
+      handleTxOp((TxOp)cmd);
+      // check that if we have left a transaction, then the connection list is empty
+      assert inTransaction || transConnections.isEmpty();
+      // check that if we are still in a transaction, then the connection list has not changed
+      assert !inTransaction || activeConnections == transConnections.size();
+    }
+  }
+
+
+  /**
+   * This method wraps the simple loop of applying a command to all transaction connections.
+   * The wrapping is done to attempt the operation on all connections, despite exceptions
+   * being thrown.
+   * @param op The operation to end the transaction.
+   * @throws QueryException The operation could not be successfully performed.
+   */
+  private void handleTxOp(TxOp op) throws QueryException {
+    // used to record the first exception, if there is one.
+    QueryException qe = null;
+    String errorMessage = null;
+
+    // Operate on all outstanding transactions.
+    Iterator<Connection> c = transConnections.iterator();
+    while (c.hasNext()) {
+      try {
+        // do the work
+        op.execute(c.next());
+      } catch (QueryException e) {
+        // store the details of the first exception only
+        if (qe != null) logger.error("Discarding subsequent exception during operation: " + op.getClass().getSimpleName(), e);
+        else {
+          qe = e;
+          errorMessage = op.getResultMessage();
+        }
+      }
+    }
+    // will only get here once all connections were processed.
+    inTransaction = op.stayInTx();
+    if (!inTransaction) transConnections.clear();
+
+    // if an exception was recorded, then throw it
+    if (qe != null) {
+      // remember the error message associated with the exception
+      op.setResultMessage(errorMessage);
+      throw qe;
+    }
+  }
+
+}

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlCommandSplitter.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/TqlCommandSplitter.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlCommandSplitter.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlCommandSplitter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,100 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.itql;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+/**
+ * Splits strings with multiple commands into lists of strings containing single commands.
+ * @created Sep 11, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class TqlCommandSplitter implements CommandSplitter {
+  /** The logger. */
+  private final static Logger logger = Logger.getLogger(TqlCommandSplitter.class.getName());
+
+  /**
+   * Split a string into individual commands.
+   * @param commands A single string containing multiple commands.
+   * @return A list of strings each containing single commands.
+   */
+  public List<String> split(String commands) {
+    List<String> singleQueryList = new ArrayList<String>();
+
+    // Inside a URI?
+    boolean inUrl = false;
+    // Inside a text literal?
+    boolean inText = false;
+
+    // Start index for next single query
+    int startIndex = 0;
+
+    if (logger.isDebugEnabled()) logger.debug("About to break up query: " + commands);
+
+    commands = commands.trim();
+
+    // Iterate along the multi query and strip out the single queries.
+    for (int lineIndex = 0; lineIndex < commands.length(); lineIndex++) {
+
+      char currentChar = commands.charAt(lineIndex);
+
+      switch (currentChar) {
+
+        // Quote - end or start of a literal if not in a URI
+        // (OK so maybe it won't appear in a legal URI but let things further
+        // down handle this)
+        case '\'':
+          if (!inUrl) {
+            if (inText) {
+              // Check for an \' inside a literal
+              if ((lineIndex > 1) && (commands.charAt(lineIndex - 1) != '\\')) inText = false;
+            } else {
+              inText = true;
+            }
+          }
+          break;
+
+          // URI start - if not in a literal
+        case '<':
+          if (!inText) inUrl = true;
+          break;
+
+          // URI end - if not in a literal
+        case '>':
+          if (!inText) inUrl = false;
+          break;
+
+        case ';':
+          if (!inText && !inUrl) {
+            String singleQuery = commands.substring(startIndex, lineIndex + 1).trim();
+            startIndex = lineIndex + 1;
+            singleQueryList.add(singleQuery);
+            if (logger.isDebugEnabled()) logger.debug("Found single query: " + singleQuery);
+          }
+          break;
+
+        default:
+      }
+    }
+    
+    // Lasy query is not terminated with a ';'
+    if (startIndex < commands.length()) singleQueryList.add(commands.substring(startIndex, commands.length()));
+
+    return singleQueryList;
+  }
+
+}

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlInterpreter.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/TqlInterpreter.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlInterpreter.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlInterpreter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,1506 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.itql;
+
+// Java 2 standard packages
+import java.io.*;
+import java.net.*;
+import java.util.*;
+
+// Third party packages
+
+import org.apache.log4j.Logger; // Apache Log4J
+import org.jrdf.graph.*; // JRDF
+
+// Locally written packages
+
+// Automatically generated packages (SableCC)
+import org.mulgara.itql.analysis.*;
+import org.mulgara.itql.lexer.*;
+import org.mulgara.itql.node.*;
+import org.mulgara.itql.parser.*;
+import org.mulgara.query.operation.AddAlias;
+import org.mulgara.query.operation.ApplyRules;
+import org.mulgara.query.operation.Backup;
+import org.mulgara.query.operation.Command;
+import org.mulgara.query.operation.Commit;
+import org.mulgara.query.operation.CreateGraph;
+import org.mulgara.query.operation.Deletion;
+import org.mulgara.query.operation.DropGraph;
+import org.mulgara.query.operation.ExecuteScript;
+import org.mulgara.query.operation.Help;
+import org.mulgara.query.operation.Insertion;
+import org.mulgara.query.operation.Load;
+import org.mulgara.query.operation.Modification;
+import org.mulgara.query.operation.Quit;
+import org.mulgara.query.operation.Restore;
+import org.mulgara.query.operation.Rollback;
+import org.mulgara.query.operation.SetAutoCommit;
+import org.mulgara.query.operation.SetTime;
+import org.mulgara.query.operation.SetUser;
+import org.mulgara.parser.Interpreter;
+import org.mulgara.parser.MulgaraLexerException;
+import org.mulgara.parser.MulgaraParserException;
+import org.mulgara.query.*;
+import org.mulgara.query.rdf.*;
+import org.mulgara.server.Session;
+
+
+/**
+ * Interactive TQL (ITQL) command interpreter.
+ * <p>
+ * Performs parsing and converting TQL requests to query objects for execution;
+ * Based on ItqlInterpreter.
+ * </p>
+ *
+ * @created 2007-08-09
+ * @author Paul Gearon
+ * @copyright &copy;2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class TqlInterpreter extends DepthFirstAdapter implements SableCCInterpreter, Aliasing {
+
+  /** The logger */
+  static final Logger logger = Logger.getLogger(TqlInterpreter.class.getName());
+
+  /** A constraint expression builder. */
+  private ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(this);
+
+  /** Variable factory for this interpreter. */
+  private VariableFactory variableFactory = new VariableFactoryImpl();
+
+  /** Lexer... */
+  Lexer2 lexer = new Lexer2();
+
+  //
+  // Members
+  //
+
+  /** The map from targets to aliases */
+  private Map<String,URI> aliasMap = null;
+
+  /** The log file to record all iTQL requests */
+  private PrintWriter itqlLog = null;
+
+  /** The location of the log iTQL file */
+  private String itqlLogFile = null;
+
+  /** The command for the callbacks to fill, while parseCommand is running */
+  Command lastCommand = null;
+  
+  /** The last exception or error, to be filled in during the callback operations. */
+  Throwable lastError = null;
+
+  //
+  // Interpreter options
+  //
+
+
+  /** The next anonymous variable suffix. */
+  private int anonSuffix = 0;
+
+  //
+  // Constructors
+  //
+
+  /**
+   * Creates a new ITQL command interpreter, using the default alias set.
+   */
+  public TqlInterpreter() {
+    this(getDefaultAliases());
+  }
+
+
+  /**
+   * Creates a new ITQL command interpreter.
+   *
+   * @param aliasMap the map from targets to aliases, never <code>null</code>
+   */
+  public TqlInterpreter(Map<String,URI> aliasMap) {
+
+    // validate aliasMap parameter
+    if (aliasMap == null) throw new IllegalArgumentException("Null \"alias\" parameter");
+
+    // set members
+    setAliasMap(aliasMap);
+
+    // log the creation of this interpreter
+    if (logger.isDebugEnabled()) {
+      logger.debug("Itql interpreter created");
+    }
+
+    // is this session configured for logging.
+    if (System.getProperty("itql.command.log") != null) {
+      itqlLogFile = System.getProperty("itql.command.log");
+      logger.info("iTQL command logging has been enabled.  Logging to " + System.getProperty("itql.command.log"));
+    }
+  }
+
+  /**   
+   * Set up default aliases.
+   *
+   * @return A map of aliases to their fully qualified names
+   */        
+  public static Map<String,URI> getDefaultAliases() {
+    Map<String,URI> aliases = new HashMap<String,URI>();
+    aliases.put(RDF, URI.create(RDF_NS));
+    aliases.put(RDFS, URI.create(RDFS_NS));
+    aliases.put(OWL, URI.create(OWL_NS));
+    aliases.put(MULGARA, URI.create(MULGARA_NS));
+    aliases.put(KRULE, URI.create(KRULE_NS));
+    aliases.put(DC, URI.create(DC_NS));
+    return aliases;
+  }  
+
+
+  //
+  // Public API
+  //
+
+  /**
+   * Parses the given TQL command.
+   *
+   * @param command the command to parse in TQL syntax
+   * @return An AST for the command
+   * @throws MulgaraParserException if the syntax of the command is incorrect
+   * @throws LexerException if the syntax of the command is incorrect
+   * @throws IOException if the <var>command</var> cannot be parsed
+   * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
+   */
+  public Command parseCommand(String command) throws MulgaraParserException, MulgaraLexerException, IOException {
+
+    // validate command parameter
+    if ((command == null) || command.equals("")) {
+      throw new IllegalArgumentException("Null \"command\" parameter");
+    }
+
+    // log that we're going to execute the command
+    if (logger.isDebugEnabled()) logger.debug("Parsing command " + command);
+
+    // Reset the variable incrementer in the query.
+    variableFactory.reset();
+
+    // log the iTQL command - system property itql.command.log must be set
+
+    // log the command abd push it into the lexer
+    this.logItql(command);
+    try {
+      lexer.add(command);
+    } catch (LexerException le) {
+      throw new MulgaraLexerException(le.getMessage(), le);
+    }
+    // test that this is a single command
+    if (lexer.getCommandCount() > 1) logger.warn("Multiple commands given to parser");
+
+    try {
+      // if the lexer saw terminators, parse the associated commands
+      if (lexer.nextCommand()) {
+  
+        Start commandTree = null;
+  
+        // parse the command
+        Parser parser = new Parser(lexer);
+        commandTree = parser.parse();
+
+        // Build the command. This populates lastCommand
+        resetInterpreter();
+        commandTree.apply(this);
+
+        if (logger.isDebugEnabled()) logger.debug("Successfully parsed command " + command);
+      }
+    } catch (LexerException le) {
+      throw new MulgaraLexerException(le);
+    } catch (ParserException pe) {
+      throw new MulgaraParserException(pe);
+    } finally {
+      flush();
+    }
+    
+    return lastCommand;
+  }
+
+
+  /**
+   * Parses the given TQL command.
+   *
+   * @param command the command to parse in TQL syntax
+   * @return A {@link List} of ASTs, one for each command
+   * @throws MulgaraParserException if the syntax of the command is incorrect
+   * @throws LexerException if the syntax of the command is incorrect
+   * @throws IOException if the <var>command</var> cannot be paersed
+   * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
+   */
+  public List<Command> parseCommands(String command) throws MulgaraParserException, MulgaraLexerException, IOException {
+
+    // validate command parameter
+    if ((command == null) || command.equals("")) {
+      throw new IllegalArgumentException("Null \"command\" parameter");
+    }
+
+    // log that we're going to execute the command
+    if (logger.isDebugEnabled()) logger.debug("Parsing command " + command);
+
+    // log the iTQL command - system property itql.command.log must be set
+    this.logItql(command);
+
+    // Reset the variable incrementer in the query.
+    variableFactory.reset();
+
+    // push the command into the lexer
+    try {
+      lexer.add(command);
+    } catch (LexerException le) {
+      throw new MulgaraLexerException(le);
+    }
+
+    // create a list of AST versions of the command
+    List<Command> commandList = new LinkedList<Command>();
+
+    // if the lexer saw terminators, parse the associated commands
+    while (lexer.nextCommand()) {
+
+      Start commandTree = null;
+
+      // parse the command
+      try {
+        Parser parser = new Parser(lexer);
+        commandTree = parser.parse();
+
+        // build the command
+        // this populates lastCommand
+        resetInterpreter();
+        commandTree.apply(this);
+        // take the lastCommand result, and add it to the list of results
+        commandList.add(lastCommand);
+
+        if (logger.isDebugEnabled()) logger.debug("Successfully parsed command " + command);
+
+      } catch (ParserException e) {
+        flush();
+        throw new MulgaraParserException(e);
+      } catch (LexerException e) {
+        flush();
+        throw new MulgaraLexerException(e);
+      } catch (Error e) {
+        flush();
+        throw e;
+      }
+
+    }
+    return commandList;
+  }
+
+
+  /**
+   * Parse a string into a {@link Query}.  Convenience method over parseCommand.
+   *
+   * @param queryString a string containing an ITQL query
+   * @return the corresponding {@link Query} instance
+   * @throws IOException if <var>queryString</var> can't be buffered.
+   * @throws LexerException if <var>queryString</var> can't be tokenized.
+   * @throws MulgaraParserException if <var>queryString</var> is not syntactic.
+   */
+  public Query parseQuery(String queryString) throws IOException,
+      MulgaraLexerException, MulgaraParserException {
+
+    if (queryString == null) throw new IllegalArgumentException("Null \"queryString\" parameter");
+
+    // clean up query
+    queryString = queryString.trim();
+    while (queryString.endsWith(";")) {
+      queryString = queryString.substring(0, queryString.length() - 1);
+    }
+
+    // log that we're going to execute the command
+    if (logger.isDebugEnabled()) logger.debug("Parsing query \"" + queryString + "\"");
+
+    // parse the command via double dispatch
+    Parser parser = new Parser(new Lexer(new PushbackReader(new StringReader(queryString), 256)));
+    resetInterpreter();
+    try {
+      parser.parse().apply(this);
+    } catch (LexerException le) {
+      throw new MulgaraLexerException(le);
+    } catch (ParserException pe) {
+      throw new MulgaraParserException(pe);
+    }
+
+    // should now have the command parsed into lastCommand.
+    // check the the command worked as expected
+    if (lastCommand == null) throw new MulgaraParserException("Parameter was not a query");
+    if (!(lastCommand instanceof Query)) throw new IllegalArgumentException("Command was not a query: " + queryString);
+
+    // return the results of the command
+    return (Query)lastCommand;
+  }
+
+
+  //
+  // Methods overridden from DepthFirstAdapter
+  // Provides callback mechanism for SableCC
+  //
+
+  /**
+   * Displays help information to the user.
+   *
+   * @param node the help command
+   */
+  public void outAHelpCommand(AHelpCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing help command " + node);
+
+    lastCommand = new Help(HelpPrinter.getHelp(node.getCommandPrefix()));
+  }
+
+
+  /**
+   * Quits a session.
+   *
+   * @param node the quit command
+   */
+  public void outAQuitCommand(AQuitCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing quit command " + node);
+
+    lastCommand = new Quit();
+  }
+
+
+  /**
+   * Commits a transaction.
+   *
+   * @param node the commit command
+   */
+  public void outACommitCommand(ACommitCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing commit command " + node);
+
+    lastCommand = new Commit();
+  }
+
+
+  /**
+   * Rolls back a transaction.
+   *
+   * @param node the rollback command
+   */
+  public void outARollbackCommand(ARollbackCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing rollback command " + node);
+    lastCommand = new Rollback();
+  }
+
+
+  /**
+   * Creates a query.
+   *
+   * @param node the query command
+   */
+  public void outASelectCommand(ASelectCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing select command " + node);
+
+    resetInterpreter();
+
+    // build the query
+    try {
+      lastCommand = this.buildQuery(node.getQuery());
+    } catch (QueryException qe) {
+      logger.warn("Couldn't answer query", qe);
+      lastError = qe;
+    } catch (URISyntaxException use) {
+      logger.warn("Invalid resource URI. " + use.getMessage());
+      lastError = use;
+    }
+  }
+
+
+  /**
+   * Substitutes the user associated with this session.
+   *
+   * @param node the su command
+   */
+  public void outASuCommand(ASuCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing su command " + node);
+
+    lastCommand = new SetUser(node.getUser().getText(), node.getPassword().getText(), toURI(node.getResource()));
+  }
+
+
+  /**
+   * Associates an alias prefix with a target.
+   *
+   * @param node the alias command
+   */
+  public void outAAliasCommand(AAliasCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing alias command " + node);
+
+    // get the prefix and target
+    String aliasPrefix = node.getPrefix().getText();
+    String aliasTarget = node.getTarget().getText();
+
+    try {
+
+      // convert the target to a URI
+      URI aliasTargetURI = new URI(aliasTarget);
+
+      // log the conversion
+      if (logger.isDebugEnabled()) logger.debug("Converted " + aliasTarget + " to URI " + aliasTargetURI);
+
+      // add the alias pair to the map
+      this.addAliasPair(aliasPrefix, aliasTargetURI);
+
+      // log that we've added the pair to the map
+      if (logger.isDebugEnabled()) logger.debug("Aliased " + aliasTarget + " as " + aliasPrefix);
+
+      // Return an AST element, for reporting on what happened.
+      lastCommand = new AddAlias(aliasPrefix, aliasTarget);
+
+    } catch (URISyntaxException use) {
+      // log the failed URI creation
+      logger.warn("Unable to create URI from alias target " + aliasTarget);
+    }
+  }
+
+
+  /**
+   * Applies a set of rules in a model to data in another model.
+   *
+   * @param node the alias command
+   */
+  public void outAApplyCommand(AApplyCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing apply command " + node);
+
+    // get the rule graph and target graph
+    URI ruleGraph = toURI(node.getRules());
+    URI baseGraph = toURI(node.getBase());
+    Token dest = node.getDestination();
+    URI destGraph = (dest == null) ? baseGraph : toURI(dest);
+
+    lastCommand = new ApplyRules(ruleGraph, baseGraph, destGraph);
+  }
+
+
+  /**
+   * Creates a new database/model.
+   *
+   * @param node the create command
+   */
+  public void outACreateCommand(ACreateCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing create command " + node);
+
+    // get the name of the model to create
+    URI graphURI = toURI(node.getModel());
+
+    // get the type of model to create; default to mulgara:Model is unspecified
+    URI graphTypeURI = (node.getModelType() == null)
+        ? Session.MULGARA_GRAPH_URI
+        : toURI(node.getModelType());
+
+    // log that we're asking the driver to create the resource
+    if (logger.isDebugEnabled()) logger.debug("Creating new graph " + graphURI);
+
+    graphURI = getCanonicalUriAlias(graphURI);
+
+    if (logger.isDebugEnabled()) logger.debug("Model is alias for " + graphURI);
+
+    lastCommand = new CreateGraph(graphURI, graphTypeURI);
+  }
+
+  /**
+   * Drop (delete) a database/model.
+   *
+   * @param node the drop command
+   */
+  public void outADropCommand(ADropCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing drop command " + node);
+
+    // get the name of the database/model to drop
+    lastCommand = new DropGraph(toURI(node.getResource()));
+  }
+
+  /**
+   * Load the contents of a file into a database/model.
+   *
+   * @param node the load command
+   */
+  public void outALoadCommand(ALoadCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing load command " + node);
+
+    // get constituents of the load command
+    URI sourceURI = toURI(node.getSource());
+    URI destinationURI = toURI(node.getDestination());
+    boolean locality = node.getLocality() != null && (node.getLocality() instanceof ALocalLocality);
+
+    lastCommand = new Load(sourceURI, destinationURI, locality);
+  }
+
+  /**
+   * Executes a TQL script.
+   *
+   * @param node the execute command
+   */
+  public void outAExecuteCommand(AExecuteCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing execute command " + node);
+
+    // get the name of the script to execute
+    String resource = node.getResource().getText();
+
+    try {
+      lastCommand = new ExecuteScript(new URL(resource), this);
+    } catch (MalformedURLException mue) {
+      // let the user know the problem
+      logger.warn("Invalid script source URL: " + resource);
+      lastError = mue;
+    }
+  }
+
+
+  /**
+   * Inserts a triple, model, database or the results of a query into a model or
+   * database.
+   *
+   * @param node the insert command
+   */
+  public void outAInsertCommand(AInsertCommand node) {
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing insert command " + node);
+
+    // get the resource we're inserting data into
+    URI graphURI = toURI(node.getResource());
+
+    lastCommand = buildModification(graphURI, node.getTripleFactor(), true);
+  }
+
+  /**
+   * Deletes a triple, model, database or the results of a query from a model or
+   * database.
+   *
+   * @param node the delete command
+   */
+  public void outADeleteCommand(ADeleteCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing delete command " + node);
+
+    // get the resource we're inserting data into
+    URI graphURI = toURI(node.getResource());
+
+    lastCommand = buildModification(graphURI, node.getTripleFactor(), false);
+  }
+
+
+  /**
+   * Sets an interpreter property.
+   *
+   * @param node the set command
+   */
+  public void outASetCommand(ASetCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing set command " + node);
+
+    // get the option to set
+    PSetOption option = node.getSetOption();
+
+    // log that we've got the option
+    if (logger.isDebugEnabled()) logger.debug("Found option " + option);
+
+    // get the value
+    boolean optionSet = !(node.getSetOptionMode() instanceof AOffSetOptionMode);
+
+    // set the option
+    if (option instanceof ATimeSetOption) {
+
+      if (logger.isDebugEnabled()) logger.debug("Found set time: " + (optionSet ? "on" : "off"));
+      lastCommand = new SetTime(optionSet);
+    } else if (option instanceof AAutocommitSetOption) {
+
+      if (logger.isDebugEnabled()) logger.debug("Found autocommit: " + (optionSet ? "on" : "off"));
+      lastCommand = new SetAutoCommit(optionSet);
+
+    } else {
+      lastError = new ItqlInterpreterException("Unknown interpreter option for \"SET\"");
+    }
+  }
+
+  /**
+   * Backs up the contents of a server to a local or remote file.
+   *
+   * @param node the backup command
+   */
+  public void outABackupCommand(ABackupCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing backup command " + node);
+
+    // get constituents of the backup command
+    URI sourceURI = toURI(node.getSource());
+    URI destinationURI = toURI(node.getDestination());
+    boolean locality = node.getLocality() != null && (node.getLocality() instanceof ALocalLocality);
+
+    lastCommand = new Backup(sourceURI, destinationURI, locality);
+  }
+
+  /**
+   * Restores the contents of a server from a file.
+   *
+   * @param node the restore command
+   */
+  public void outARestoreCommand(ARestoreCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing restore command " + node);
+
+    URI destinationURI = toURI(node.getDestination());
+    URI sourceURI = toURI(node.getSource());
+    boolean locality = node.getLocality() != null && (node.getLocality() instanceof ALocalLocality);
+
+    lastCommand = new Restore(sourceURI, destinationURI, locality);
+  }
+
+  /**
+   * Returns a set of statements from the iTQL query object.
+   *
+   * @param setOfTriples the set of statements defined in the query.
+   * @param variableMap the variable map to store the value of the variable
+   *   against the variable object.
+   * @throws URISyntaxException if <code>tripleFactor</code> contains a query or
+   *      a resource that that violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC\uFFFD2396</a>
+   * @throws QueryException if an invalid node is used in the set of triples.
+   * @return a set of statements from the iTQL query.
+   */
+  @SuppressWarnings("unchecked")
+  public Set<org.jrdf.graph.Triple> getStatements(ATripleSetOfTriples setOfTriples, Map<String,VariableNodeImpl> variableMap)
+      throws QueryException, URISyntaxException {
+  
+    List<ATriple> tripleList = (List<ATriple>)setOfTriples.getTriple();
+    HashSet<org.jrdf.graph.Triple> statements = new HashSet<org.jrdf.graph.Triple>();
+  
+    // Check that each set of triples has the predicate bound.
+    for (Iterator<ATriple> i = tripleList.iterator(); i.hasNext(); ) {
+  
+      // get the triple
+      ATriple triple = i.next();
+  
+      // Convert the Subject, Predicate and Object.
+      org.jrdf.graph.Node subject = toNode(triple.getSubject(), variableMap);
+      org.jrdf.graph.Node predicate = toNode(triple.getPredicate(), variableMap);
+      org.jrdf.graph.Node object = toNode(triple.getObject(), variableMap);
+  
+      // Predicate cannot be a blank node.
+      if (predicate instanceof BlankNode) {
+        throw new QueryException("Predicate must be a valid URI");
+      }
+  
+      // Check that the subject or predicate node is not a literal.
+      if (subject instanceof LiteralImpl ||
+          predicate instanceof LiteralImpl) {
+  
+        // throw an exception indicating we have a bad triple
+        throw new QueryException(
+            "Subject or Predicate cannot be a literal");
+      }
+  
+      // Create a new statement using the triple elements
+      org.jrdf.graph.Triple jrdfTriple = new TripleImpl(
+          (SubjectNode) subject, (PredicateNode) predicate,
+          (ObjectNode) object);
+  
+      // add the statement to the statement set
+      statements.add(jrdfTriple);
+    }
+  
+    return statements;
+  }
+
+
+  /**
+   * Creates a query from iTQL syntax and grammar.
+   * Despite onyl being accessed from within this package (both locally and from
+   * {@link VariableBuilder}) this method must be public, as it has to appear in
+   * the {@link Interpreter} interface.
+   *
+   * @param rawQuery a select query, represented as either a {@link
+   *      org.mulgara.itql.node.ASelectCommand} or a {@link
+   *      org.mulgara.itql.node.ASelectSetOfTriples}
+   * @return the answer to the query
+   * @throws QueryException if the query cannot be executed
+   * @throws URISyntaxException if the <code>query</code> contains a resource
+   *      whose text violates <a href="http://www.isi.edu/in-notes/rfc2396.txt">
+   *      RFC\uFFFD2396</a>
+   */
+  @SuppressWarnings("unchecked")
+  public Query buildQuery(org.mulgara.itql.node.Node rawQuery) throws QueryException, URISyntaxException {
+  
+    // validate query parameter
+    if (rawQuery == null) throw new IllegalArgumentException("Null \"rawQuery\" parameter");
+  
+    // create the variables.  May contain a PElement; Count; URI literal; or a sub query
+    LinkedList<PElement> variables = null;
+    AFromClause fromClause;
+    AWhereClause whereClause;
+    AOrderClause orderClause;
+    AHavingClause havingClause;
+    ALimitClause limitClause;
+    AOffsetClause offsetClause;
+  
+    // cast the correct way (we don't have a common superclass, event though we
+    // have methods with the same names)
+    if (rawQuery instanceof AQuery) {
+  
+      AQuery query = (AQuery) rawQuery;
+      PSelectClause selectClause = query.getSelectClause();
+      if (selectClause instanceof ANormalSelectSelectClause) {
+        variables = (LinkedList<PElement>)((ANormalSelectSelectClause)selectClause).getElement();
+      }
+      fromClause = ((AFromClause)query.getFromClause());
+      whereClause = ((AWhereClause)query.getWhereClause());
+      orderClause = ((AOrderClause)query.getOrderClause());
+      havingClause = ((AHavingClause)query.getHavingClause());
+      limitClause = ((ALimitClause)query.getLimitClause());
+      offsetClause = ((AOffsetClause)query.getOffsetClause());
+    } else if (rawQuery instanceof ASelectSetOfTriples) {
+  
+      ASelectSetOfTriples query = (ASelectSetOfTriples) rawQuery;
+      variables = new LinkedList<PElement>();
+      variables.add(query.getSubject());
+      variables.add(query.getPredicate());
+      variables.add(query.getObject());
+      fromClause = ((AFromClause)query.getFromClause());
+      whereClause = ((AWhereClause)query.getWhereClause());
+      orderClause = ((AOrderClause)query.getOrderClause());
+      havingClause = ((AHavingClause)query.getHavingClause());
+      limitClause = ((ALimitClause)query.getLimitClause());
+      offsetClause = ((AOffsetClause)query.getOffsetClause());
+    } else {
+  
+      // we only handle AQuery and ASelectSetOfTriples
+      throw new IllegalArgumentException("Invalid type for \"rawQuery\" parameter");
+    }
+  
+    if (fromClause == null) throw new QueryException("FROM clause missing.");
+    if (whereClause == null) throw new QueryException("WHERE clause missing.");
+
+    // build the variable list: collection of Variable, ConstantValue, Count, Subquery
+    if (logger.isDebugEnabled()) logger.debug("Building query variable list from " + variables);
+    List<SelectElement> variableList = this.buildVariableList(variables);
+    if (logger.isDebugEnabled()) logger.debug("Built variable list " + variableList);
+  
+    // get the model expression from the parser
+    PModelExpression rawModelExpression = fromClause.getModelExpression();
+    if (logger.isDebugEnabled()) logger.debug("Building model expression from " + rawModelExpression);
+    // parse the text into a model expression
+    ModelExpression modelExpression = ModelExpressionBuilder.build(this.getAliasMap(), rawModelExpression);
+    if (logger.isDebugEnabled()) logger.debug("Built model expression " + modelExpression);
+  
+    // get the constraint expression from the parser
+    PConstraintExpression rawConstraintExpression = whereClause.getConstraintExpression();
+    if (logger.isDebugEnabled()) logger.debug("Building constraint expression from " + rawConstraintExpression);
+    // parse the text into a constraint expression
+    ConstraintExpression constraintExpression = build(rawConstraintExpression);
+    if (logger.isDebugEnabled()) logger.debug("Built constraint expression " + constraintExpression);
+  
+    // build the order list
+    List<Order> orderList = buildOrderList(orderClause);
+
+    // build the having clause
+    ConstraintHaving havingExpression = buildHaving(havingClause);
+  
+  
+    // build the limit and offset
+    Integer limit = null;
+    int offset = 0;
+    try {
+      if (limitClause != null) limit = new Integer(limitClause.getNumber().getText());
+      if (offsetClause != null) offset = Integer.parseInt(offsetClause.getNumber().getText());
+    } catch (NumberFormatException e) {
+      String failedType = (limit == null) ? "limit" : "offset";
+      throw new Error("Parser permitted non-integer for " + failedType, e);
+    }
+  
+    // build a query using the information we've obtained from the parser
+    return new Query(variableList, modelExpression, constraintExpression,
+        havingExpression, orderList, limit, offset, new UnconstrainedAnswer());
+  }
+
+
+  /**
+   * @see org.mulgara.itql.QueryInterpreter#toLiteralImpl(org.mulgara.itql.node.PLiteral)
+   * Despite onyl being accessed from within this package (both locally and from
+   * {@link VariableBuilder}) this method must be public, as it has to appear in
+   * the {@link Interpreter} interface.
+   */
+  public LiteralImpl toLiteralImpl(PLiteral p) {
+  
+    ALiteral aLiteral = (ALiteral)p;
+  
+    // Determine the datatype URI, if present
+    ADatatype type = (ADatatype)aLiteral.getDatatype();
+    URI datatypeURI = (type != null) ? toURI(type.getResource()) : null;
+  
+    if (datatypeURI != null) {
+      return new LiteralImpl(getLiteralText(aLiteral), datatypeURI);
+    } else {
+      // Determine the language code
+      String language = toLanguageId((ALanguage)aLiteral.getLanguage());
+      if (language != null) return new LiteralImpl(getLiteralText(aLiteral), language);
+      // no language, so return an untyped, no language literal
+      return new LiteralImpl(getLiteralText(aLiteral));
+    }
+  }
+
+
+  /**
+   * @see org.mulgara.itql.QueryInterpreter#toURI(org.mulgara.itql.node.Token)
+   */
+  public URI toURI(Token token) {
+  
+    assert token instanceof TResource;
+    return URIUtil.convertToURI(token.getText(), aliasMap);
+  }
+
+
+  /**
+   * @see org.mulgara.itql.QueryInterpreter#nextAnonVariable()
+   * Called by {@link ConstraintExpressionBuilder}
+   */
+  public Variable nextAnonVariable() {
+    return new Variable("av__" + this.anonSuffix++);
+  }
+
+  
+  /**
+   * Builds a {@link org.mulgara.query.ConstraintExpression} object from a
+   * {@link org.mulgara.itql.node.PConstraintExpression}, using an <code>aliasMap</code>
+   * to resolve aliases.  Uses double-dispatch into the AST for the expression.
+   *
+   * @param expression a constraint expression from the parser
+   * @return A new constraint expression, based on the AST passed as "expression".
+   * @throws QueryException if <code>rawConstraintExpression</code> does not
+   *      represent a valid query
+   * @throws URISyntaxException if the <code>rawConstraintExpression</code>
+   *      contains a resource whose text violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
+   */
+  public ConstraintExpression build(PConstraintExpression expression) throws
+      QueryException, URISyntaxException {
+  
+    // validate parameters
+    if (aliasMap == null) throw new IllegalArgumentException("Null \"aliasMap\" parameter");
+    if (expression == null) throw new IllegalArgumentException("Null \"expression\" parameter");
+  
+    if (logger.isDebugEnabled()) logger.debug("Building constraint expression from " + expression);
+  
+    // build the contraint expression from the parser input
+    expression.apply((Switch)builder);
+    ConstraintExpression constraintExpression = builder.getConstraintExpression();
+    if (logger.isDebugEnabled()) logger.debug("Successfully built constraint expression from " + expression);
+  
+    // return the new constraint expression
+    return constraintExpression;
+  }
+
+
+  /**
+   * Returns the text of the given <code>literal</code>.
+   *
+   * @param literal the literal to retrieve the text from
+   * @return The LiteralText value
+   */
+  @SuppressWarnings("unchecked")
+  public static String getLiteralText(ALiteral literal) {
+  
+    // validate the literal parameter
+    if (literal == null) throw new IllegalArgumentException("Null \"literal\" " + "parameter");
+  
+    // the text of the literal
+    StringBuffer literalText = new StringBuffer();
+  
+    // get all the strands in this literal
+    List<PStrand> strands = (List<PStrand>)literal.getStrand();
+  
+    // add each strand together to make the literal text
+    for (PStrand strand: strands) {
+      
+      // add the strand to the literal text
+      if (strand instanceof AUnescapedStrand) {
+        literalText.append(((AUnescapedStrand)strand).getText().getText());
+      } else if (strand instanceof AEscapedStrand) {
+        literalText.append(((AEscapedStrand)strand).getEscapedtext().getText());
+      }
+    }
+
+    return literalText.toString();
+  }
+
+
+  /**
+   * Sets the alias map associated with this interpreter.
+   *
+   * @param aliasMap the alias map associated with this interpreter
+   */
+  public void setAliasMap(Map<String,URI> aliasMap) {
+    this.aliasMap = aliasMap;
+  }
+
+
+  /**
+   * Returns the alias map associated with this session.
+   *
+   * @return the alias namespace map associated with this session
+   */
+  public Map<String,URI> getAliasMap() {
+    return aliasMap;
+  }
+
+
+  /**
+   * Builds a list of {@link org.mulgara.query.Variable}s from a list of
+   * {@link org.mulgara.itql.node.PVariable}s. Note. Variables in both the
+   * <code>rawVariableList</code> and the returned list will <strong>not
+   * </strong> contain the variable prefix <code>$</code> in their name.
+   *
+   * @param rawVariableList a list of {@link
+   *      org.mulgara.itql.node.PVariable}s from the parser
+   * @return a list of {@link org.mulgara.query.Variable}s, suitable for use
+   *      in creating a {@link org.mulgara.query.Query}
+   * @throws QueryException if the <code>rawVariableList</code> cannot be parsed
+   *      into a list of {@link org.mulgara.query.Variable}s
+   */
+  @SuppressWarnings("unchecked")
+  List<SelectElement> buildVariableList(LinkedList<PElement> rawVariableList) throws
+      QueryException, URISyntaxException {
+  
+    // Empty variable list.
+    if (rawVariableList == null) return Collections.emptyList();
+  
+    // validate rawVariableList parameter
+    if (rawVariableList.size() == 0) throw new IllegalArgumentException("Empty \"rawVariableList\" parameter");
+  
+    // Construct the required builder
+    VariableBuilder variableBuilder = new VariableBuilder(this, variableFactory);
+  
+    // end if
+    // log that we're building the variable list
+    if (logger.isDebugEnabled()) logger.debug("Building variable list from " + rawVariableList);
+  
+    // copy each variable from the query into the list
+    for (PElement element: rawVariableList) element.apply((Switch)variableBuilder);
+  
+    // Get the variable list
+    List<SelectElement> variableList = variableBuilder.getVariableList();
+  
+    // make sure that we return a list with something in it
+    if (variableList.size() == 0) {
+      throw new QueryException("No variables parseable from query");
+    }
+  
+    // log that we've successfully built the variable list
+    if (logger.isDebugEnabled()) {
+      logger.debug("Built variable list " + variableList);
+    }
+  
+    // return the list
+    return variableList;
+  }
+
+  /**
+   * Builds a list of {@link org.mulgara.query.Variable}s from a list of
+   * {@link org.mulgara.itql.node.POrderElement}s. Note. Variables in both
+   * the <code>rawVariableList</code> and the returned list will <strong>not
+   * </strong> contain the variable prefix <code>$</code> in their name.
+   *
+   * @param rawOrderList The SableCC list of elements to order by.
+   * @return a list of {@link org.mulgara.query.Variable}s, suitable for use
+   *      in creating a {@link org.mulgara.query.Query}, or an empty list if
+   *      there are no elements to be ordered by.
+   * @throws QueryException if the <code>rawOrderElementList</code> cannot be
+   *      parsed into a list of {@link org.mulgara.query.Variable}s
+   */
+  @SuppressWarnings("unchecked")
+  List<Order> buildOrderList(AOrderClause orderClause) throws QueryException {
+
+    // short circuit for an empty clause 
+    if (orderClause == null) return (List<Order>)Collections.EMPTY_LIST;
+    
+    // get the list of elements in the clause
+    LinkedList<AOrderElement> rawOrderList = (LinkedList<AOrderElement>)orderClause.getOrderElement();
+    
+    assert rawOrderList != null && !rawOrderList.isEmpty();
+  
+    if (logger.isDebugEnabled()) logger.debug("Building order list from " + rawOrderList);
+  
+    // create a list for the parsed variables
+    List<Order> orderList = new ArrayList<Order>(rawOrderList.size());
+  
+    // copy each variable from the query into the list
+    for (AOrderElement order: rawOrderList) {
+
+      // get the name of this variable
+      String variableName = ((AVariable)order.getVariable()).getIdentifier().getText();
+  
+      if (logger.isDebugEnabled()) logger.debug("Found variable $" + variableName);
+  
+      // Figure out which way to order, ascending or descending
+      boolean ascending;
+      PDirection direction = order.getDirection();
+  
+      if (direction == null) {
+        ascending = true;
+      } else if (direction instanceof AAscendingDirection) {
+        ascending = true;
+      } else if (direction instanceof ADescendingDirection) {
+        ascending = false;
+      } else {
+        throw new Error("Unknown direction field in order");
+      }
+  
+      // add a new ordered variable to the list
+      orderList.add(new Order(new Variable(variableName), ascending));
+    }
+  
+    // make sure that we return a list with something in it
+    if (orderList.size() == 0) throw new QueryException("No variables parseable from query");
+  
+    if (logger.isDebugEnabled()) logger.debug("Built order list " + orderList);
+    return orderList;
+  }
+
+
+  /**
+   * Builds a HAVING compliant {@link org.mulgara.query.ConstraintExpression} object from a
+   * {@link org.mulgara.itql.node.PConstraintExpression}, using an <code>aliasMap</code>
+   * to resolve aliases.  To comply with a HAVING clause the predicate must be one of:
+   * mulgara:occurs mulgara:occursLessThan mulgara:occursMoreThan.
+   *
+   * @param expression a constraint expression from the parser
+   * @return A new ConstraintExpression representing the HAVING condition
+   * @throws QueryException if <code>rawConstraintExpression</code> does not
+   *      represent a valid query
+   * @throws URISyntaxException if the <code>rawConstraintExpression</code>
+   *      contains a resource whose text violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
+   */
+  ConstraintHaving buildHaving(AHavingClause havingClause) throws QueryException, URISyntaxException {
+  
+    // short circuit if there is no having clause
+    if (havingClause == null) return null;
+    
+    // get the constraint expression from the parser
+    PConstraintExpression rawHavingExpression = havingClause.getConstraintExpression();
+    if (logger.isDebugEnabled()) logger.debug("Building constraint expression from " + rawHavingExpression);
+  
+    ConstraintExpression hExpr = build(rawHavingExpression);
+  
+    // do some gramatical checking on the clause
+    if (hExpr instanceof ConstraintOperation) throw new QueryException("Having currently supports only one constraint");
+    if (!checkHavingPredicates(hExpr)) throw new QueryException("Only \"occurs\" predicates can be used in a Having clause");
+  
+    return (ConstraintHaving)hExpr;
+  }
+
+  /**
+   * Convert a literal's language node into a language ID
+   * @param language The node containing the language node.
+   * @return The 2 or 5 character identifier, or <code>null</code> if no code available.
+   * @throws QueryException if the ID of the language is malformed.
+   */
+  private static String toLanguageId(ALanguage language) {
+    if (language == null) return null;
+    String langId = language.getLangid().getText();
+    int len = langId.length();
+    if (len != 2 && len != 5) {
+      logger.error("Unknown form for language tag: " + langId);
+      langId = null;
+    }
+    return langId;
+  }
+
+
+  /**
+   * Resets the parser state in preparation for a new command.
+   */
+  private void resetInterpreter() {
+    lastCommand = null;
+    lastError = null;
+  }
+  
+  
+  /**
+   * @param graphURI
+   * @param tripleFactor
+   */
+  private Modification buildModification(URI graphURI, PTripleFactor tripleFactor, boolean asserting) {
+    // get the set of triples out of the factor
+    PSetOfTriples setOfTriples = null;
+    if (tripleFactor instanceof ABracedTripleFactor) {
+      setOfTriples = ((ABracedTripleFactor)tripleFactor).getSetOfTriples();
+    } else if (tripleFactor instanceof AUnbracedTripleFactor) {
+      setOfTriples = ((AUnbracedTripleFactor)tripleFactor).getSetOfTriples();
+    } else throw new RuntimeException("Unhandled Grammar Exception: Unknown type of triple factor: " + tripleFactor.getClass().getName());
+
+    try {
+      // Create the correct type of modifier for the data 
+      if (setOfTriples instanceof AResourceSetOfTriples) {
+        // this is an insert of one model into another.
+        throw new UnsupportedOperationException("No support for direct model to model insertion.");
+      } else if (setOfTriples instanceof ASelectSetOfTriples) {
+        // This is an INSERT/SELECT
+        // build the query
+        Query query = this.buildQuery((ASelectSetOfTriples)setOfTriples);
+        if (logger.isDebugEnabled()) logger.debug("Insert query " + query);
+        return newModifier(graphURI, query, asserting);
+      } else if (setOfTriples instanceof ATripleSetOfTriples) {
+        // This is an inline set of triples
+        Set<Triple> statements = getStatements((ATripleSetOfTriples)setOfTriples, new HashMap<String,VariableNodeImpl>());
+        return newModifier(graphURI, statements, asserting);
+      }
+    } catch (URISyntaxException ue) {
+      logger.warn("Invalid URL in the insertion data: " + ue.getMessage());
+      lastError = ue;
+    } catch (QueryException qe) {
+      logger.warn("Bad query for insertion: " + qe.getMessage());
+      lastError = qe;
+    }
+    return null;
+  }
+
+  
+  /**
+   * Factory method to create a Modification object.
+   * @param graphURI The URI of the graph to be modified.
+   * @param query The query to select the data to be modified.
+   * @param asserting Indicates if the data needs to be asserted (inserted)
+   *        or denied (deleted).
+   * @return An {@link Insertion} if asserting is <code>true</code>,
+   *         otherwise a {@link Deletion}.
+   */
+  private Modification newModifier(URI graphURI, Query query, boolean asserting) {
+    return asserting ? new Insertion(graphURI, query) : new Deletion(graphURI, query);
+  }
+
+
+  /**
+   * Factory method to create a Modification object.
+   * @param graphURI The URI of the graph to be modified.
+   * @param statements A set of triples to be modified.
+   * @param asserting Indicates if the data needs to be asserted (inserted)
+   *        or denied (deleted).
+   * @return An {@link Insertion} if asserting is <code>true</code>,
+   *         otherwise a {@link Deletion}.
+   */
+  private Modification newModifier(URI graphURI, Set<Triple> statements, boolean asserting) {
+    return asserting ? new Insertion(graphURI, statements) : new Deletion(graphURI, statements);
+  }
+
+
+  /**
+   * Constructs a {@link org.jrdf.graph.Node} from a {@link
+   * org.mulgara.itql.node.PTripleElement}.
+   *
+   * @param element dd
+   * @param variableMap a {@link Map} of variable names (as string) to
+   *   {@link VariableNodeImpl} that are used to contain all variables.
+   * @return dd
+   * @throws QueryException if <code>element</code> is a {@link
+   *   org.mulgara.itql.node.AResourceTripleElement} whose text contains a
+   *   <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">qualified
+   *   name</a> with a prefix not defined in the <code>aliasMap</code>
+   * @throws URISyntaxException if <code>element</code> is a {@link
+   *   org.mulgara.itql.node.AResourceTripleElement} whose text doesn't
+   *   conform to <a href="http://www.isi.edu/in-notes/rfc2396.txt">
+   *   RFC\uFFFD2396</a>
+   */
+  private org.jrdf.graph.Node toNode(PTripleElement element, Map<String,VariableNodeImpl> variableMap)
+      throws QueryException, URISyntaxException {
+
+    // validate the element parameter
+    if (element == null) throw new IllegalArgumentException("Null \"element\" parameter");
+
+    if (logger.isDebugEnabled()) logger.debug("Resolving " + element + "to a RDF node");
+
+    // create the node
+    org.jrdf.graph.Node node = null;
+
+    // get the node
+    if (element instanceof ALiteralTripleElement) {
+      // create a new literal with the given text
+      node = toLiteralImpl(((ALiteralTripleElement)element).getLiteral());
+      
+    } else if (element instanceof AResourceTripleElement) {
+      // create a new resource
+      node = new URIReferenceImpl(toURI(((AResourceTripleElement)element).getResource()));
+      
+    } else if (element instanceof AVariableTripleElement) {
+
+      // get the variable
+      String variableName = ((AVariable)((AVariableTripleElement)element).getVariable()).getIdentifier().getText();
+
+      if (logger.isDebugEnabled()) logger.debug("Resolved " + element + " to variable " + variableName);
+
+      // use a map to keep the same variable objects if they can be reused
+      if (variableMap.containsKey(variableName)) {
+        node = (VariableNodeImpl)variableMap.get(variableName);
+      } else {
+        node = new VariableNodeImpl(variableName);
+        variableMap.put(variableName, (VariableNodeImpl)node);
+      }
+    }
+
+    // return the node
+    return node;
+  }
+
+
+  /**
+   * Adds a name/value pair to the alias map. This method will add associate a
+   * prefix for a target for subsequent commands, making commands like the
+   * following possible: <PRE>
+   * alias http://purl.org/dc/elements/1.1 as dc;
+   * select $title where $uri dc:title $title ;
+   * </PRE>
+   *
+   * @param aliasPrefix the alias that denotes the target
+   * @param aliasTarget the target associated with the prefix
+   */
+  private void addAliasPair(String aliasPrefix, URI aliasTarget) {
+
+    // validate the parameters
+    if (aliasPrefix == null) throw new IllegalArgumentException("Null \"aliasPrefix\" " + "parameter");
+    if (aliasTarget == null) throw new IllegalArgumentException("Null \"aliasTarget\" " + "parameter");
+
+    // add the pair to the map
+    getAliasMap().put(aliasPrefix, aliasTarget);
+  }
+
+
+  /**
+   * Log the TQL command to a specified file
+   *
+   * @param command The TQL command to be validated
+   */
+  private void logItql(String command) {
+
+    // Short circuit if not logging.  The constructor initialises this if
+    // system property itql.command.log is set
+    if (itqlLogFile == null) return;
+
+    try {
+      // open log if needed
+      if (itqlLog == null) itqlLog = new PrintWriter(new FileWriter(itqlLogFile, true), true);
+      // append the command to the file
+      itqlLog.println(command);
+    } catch (Exception ex) {
+      logger.error("Unable to log itql commands", ex);
+    }
+  }
+
+
+  /**
+   * Discard any unparsed tokens.
+   */
+  private void flush() {
+    lexer.leftoverTokenList.clear();
+  }
+
+
+  /**
+   * Checks that all predicates in a constraint expression are valid Having predicates
+   * from {@link SpecialPredicates}.
+   *
+   * @param e The constraint expression to check.
+   * @return true if all constraints have special predicates.
+   */
+  private boolean checkHavingPredicates(ConstraintExpression e) {
+    if (e instanceof Constraint) {
+      return e instanceof ConstraintHaving;
+    } else if (e instanceof ConstraintOperation) {
+      // check all sub expressions
+      for (ConstraintExpression expr: ((ConstraintOperation)e).getElements()) {
+        if (checkHavingPredicates(expr)) return false;
+      }
+      // all sub expressions returned true
+      return true;
+    } else {
+      // An unexpected type
+      return false;
+    }
+  }
+
+  /** Local constants list of supported protocols. */
+  private static final Set<String> protocols = new HashSet<String>();
+  static {
+    protocols.add("rmi");
+    protocols.add("soap");
+  }
+
+  /**
+   * Try to recognise a uri alias, and return the canonical form instead.
+   *
+   * @param uri The URI being checked.
+   * @return The updated URI.  May be the same as the uri parameter.
+   */
+  private URI getCanonicalUriAlias(URI uri) {
+    // only do this for remote protocols
+    if (!protocols.contains(uri.getScheme())) return uri;
+
+    logger.debug("Checking for an alias on: " + uri);
+
+    // extract the host name
+    String host = uri.getHost();
+    if (host == null) return uri;
+
+    Set<String> hostnames = getHostnameAliases();
+    // Check with a DNS server to see if this host is recognised
+    InetAddress addr = null;
+    try {
+      addr = InetAddress.getByName(host);
+    } catch (UnknownHostException uhe) {
+      // The host was unknown, so allow resolution to continue as before
+      return uri;
+    }
+    // check the various names against known aliases and the given name
+    if (
+        hostnames.contains(host) ||
+        hostnames.contains(addr.getHostName()) ||
+        hostnames.contains(addr.getCanonicalHostName()) ||
+        hostnames.contains(addr.getHostAddress())
+    ) {
+      // change the host name to one that is recognised
+      // use the system uri to find the local host name
+      URI serverURI = getServerURI();
+      if (serverURI == null) {
+        return uri;
+      }
+      String newHost = serverURI.getHost();
+      try {
+        return new URI(uri.getScheme(), newHost, uri.getPath(), uri.getFragment());
+      } catch (URISyntaxException e) { /* fall through */ }
+    }
+
+    // not found, so return nothing
+    return uri;
+  }
+
+
+  /**
+   * Method to ask the ServerInfo for the local server aliases.
+   * This will return an empty set if ServerInfo is not available -
+   * ie. being run on a host which has no local database, such an an iTQL client.
+   *
+   * @return The set of server aliases as strings
+   */
+  @SuppressWarnings("unchecked")
+  private static Set<String> getHostnameAliases() {
+    Set<String> names = (Set<String>)getServerInfoProperty("HostnameAliases");
+    return (names == null) ? (Set<String>)java.util.Collections.EMPTY_SET : names;
+  }
+
+
+  /**
+   * Method to ask the ServerInfo for the local server URI.
+   * This will return null if ServerInfo is not available -
+   * ie. being run on a host which has no local database, such an an iTQL client.
+   *
+   * @return The URI of the local server, or null if this is not a server.
+   */
+  private static URI getServerURI() {
+    return (URI)getServerInfoProperty("ServerURI");
+  }
+
+
+  /**
+   * Method to get the value of a property from the ServerInfo for the local database session.
+   * This will return null if ServerInfo is not available -
+   * ie. being run on a host which has no local database, such an an TQL client.
+   *
+   * @param property The property to return, with the correct case.
+   * @return The object returned from the accessor method named, or null if ServerInfo is not available.
+   */
+  private static Object getServerInfoProperty(String property) {
+    Object o = null;
+    try {
+      Class<?> rsf = Class.forName("org.mulgara.server.ServerInfo");
+      java.lang.reflect.Method getter = rsf.getMethod("get" + property, (Class<?>[])null);
+      o = getter.invoke(null, (Object[])null);
+    } catch (Exception e) { /* no op */ }
+    return o;
+  }
+
+  private class Lexer2 extends Lexer {
+  
+    int commandCount = 0;
+    final LinkedList<Token> leftoverTokenList = new LinkedList<Token>();
+  
+    public Lexer2() {
+      super(null);
+    }
+  
+    public int getCommandCount() {
+      return commandCount;
+    }
+  
+    public void add(String command) throws LexerException, IOException {
+      Lexer lexer = new Lexer(new PushbackReader(new StringReader(command), 256));
+      Token t;
+      while (! ( (t = lexer.next()) instanceof EOF)) {
+        if (t instanceof TTerminator) {
+          t = new EOF();
+          commandCount++;
+        }
+        leftoverTokenList.add(t);
+      }
+    }
+  
+    public Token next() throws LexerException, IOException {
+      return leftoverTokenList.isEmpty() ? new EOF() : (Token) leftoverTokenList.removeFirst();
+    }
+  
+    public Token peek() throws LexerException, IOException {
+      return leftoverTokenList.isEmpty() ? new EOF() : (Token) leftoverTokenList.getFirst();
+    }
+  
+    public boolean nextCommand() {
+      if (commandCount == 0) {
+        return false;
+      }
+      else {
+        //assert commandCount > 0;
+        commandCount--;
+        return true;
+      }
+    }
+  }
+
+}

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSession.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/TqlSession.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSession.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSession.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,628 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.itql;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.List;
+import java.util.ArrayList;
+import javax.swing.JFrame;
+import javax.swing.WindowConstants;
+import javax.xml.parsers.FactoryConfigurationError;
+
+// Third party packages
+import org.apache.log4j.BasicConfigurator;
+import org.apache.log4j.Category;
+import org.apache.log4j.xml.DOMConfigurator;
+
+import org.mulgara.query.Answer;
+import org.mulgara.query.TuplesException;
+
+
+/**
+ * Command line shell for working with TQL sessions.
+ *
+ * @created September 11, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class TqlSession {
+
+  private static final String USER_DIR = "user.dir";
+
+  private static final int DEFAULT_HEIGHT = 480;
+
+  private static final int DEFAULT_WIDTH = 640;
+
+  public static final String SHELL_NAME = "TQL Shell";
+
+  /** Line separator. */
+  private static final String EOL = System.getProperty("line.separator");
+
+  /** The prompt. */
+  public final static String PS1 = "iTQL> ";
+
+  /** The secondary prompt, indicating an incomplete command. */
+  public final static String PS2 = "      ";
+
+  /** The log4j configuration file path (within the JAR file) */
+  private final static String LOG4J_CONFIG_PATH = "log4j-tql.xml";
+
+  /** The logging category to use */
+  private final static Category log = Category.getInstance(TqlSession.class.getName());
+
+  /** The default path to the pre-loading script */
+  private final static String PRE_LOADING_SCRIPT_PATH = "default-pre.tql";
+
+  /** The default path to the post-loading script */
+  private final static String POST_LOADING_SCRIPT_PATH = "default-post.tql";
+  
+  /** The command prompt */
+  final static String PROMPT = "TQL> ";
+
+
+  /** The graphical UI. */
+  private TqlSessionUI gui;
+
+  /** The messages from the previous queries. */
+  private List<String> messages = new ArrayList<String>();
+
+  /** The answers from the previous queries. */
+  private List<Answer> answers = new ArrayList<Answer>();
+
+  /** The file name (URL) of the script to execute if -s is given. */
+  private String scriptLocation = null;
+
+  //
+  // Members
+  //
+
+  /** The TQL auto-interpreter associated with this session */
+  private final TqlAutoInterpreter autoTql;
+
+  /** The URL of the post-loading script */
+  private URL postLoadingScriptUrl = null;
+
+  /** The URL of the pre-loading script */
+  private URL preLoadingScriptUrl = null;
+
+  /** A functor for splitting commands apart. */
+  private CommandSplitter commandSplitter = null;
+
+
+  /**
+   * Start an interactive TQL session from the command prompt.
+   * @param args command line parameters
+   * @throws MalformedURLException Provided URL for a script file is invalid.
+   */
+  public static void main(String[] args) throws MalformedURLException {
+
+    // create a new session to work with
+    TqlSession tqlSession = new TqlSession();
+
+    try {
+
+      // set the default pre- and post-loading scripts
+      tqlSession.setDefaultLoadingScripts();
+
+      // parse the command line options
+      ItqlOptionParser optsParser = new ItqlOptionParser(args);
+      optsParser.parse();
+      boolean startSession = tqlSession.handleOptions(optsParser);
+
+      if (log.isDebugEnabled()) log.debug("Processed command line options");
+
+      // execute the pre-loading script - we need to do this after we get the
+      // command line options as we can override the defaults
+      tqlSession.executeLoadingScript(tqlSession.getPreLoadingScriptURL());
+
+      if (log.isDebugEnabled()) log.debug("Executed pre-loading script");
+
+      // if we can, execute this session using std in and std out
+      if (startSession) tqlSession.runInterface();
+      else {
+        // otherwise, run the scripts we were given
+        tqlSession.executeScript(tqlSession.getScript());
+        tqlSession.executeLoadingScript(tqlSession.getPostLoadingScriptURL());
+        tqlSession.close();
+      }
+
+    } catch (ItqlOptionParser.UnknownOptionException uoe) {
+      errorTermination(tqlSession, "Invalid command line option: " + uoe.getOptionName());
+    } catch (ItqlOptionParser.IllegalOptionValueException iove) {
+      String optionMsg = "-" + iove.getOption().shortForm() + ", --" + iove.getOption().longForm() + " = " + iove.getValue();
+      errorTermination(tqlSession, "Invalid command line option value specified: " + optionMsg);
+    }
+  }
+
+  
+  /**
+   * Convenience method to log errors and terminate the program.
+   * @param session The current session to close.
+   * @param message The error message to log.
+   */
+  private static void errorTermination(TqlSession session, String message) {
+    log.warn(message);
+    System.err.println(message);
+    session.printUsage(System.out);
+    session.close();
+  }
+
+  /**
+   * Constructor.  Creates a new TQL session.
+   */
+  public TqlSession() {
+    // load the default logging configuration
+    this.loadLoggingConfig();
+    autoTql = new TqlAutoInterpreter();
+    commandSplitter = new TqlCommandSplitter();
+  }
+
+
+  /**
+   * Returns a list of messages (Strings) from the execution of the last
+   * command or series of commands.  Successful and unsuccessful commands will
+   * have valid string objects.
+   * @return all the accumulated messages from the execution of the previous commands.
+   */
+  List<String> getLastMessages() {
+    return messages;
+  }
+
+
+  /**
+   * Returns a list of Answers from the execution of the last command or series
+   * of commands.  Failures will not be included.
+   * @return all the accumulated Answers from the execution of the previous commands.
+   */
+  List<Answer> getLastAnswers() {
+    return answers;
+  }
+
+
+  /**
+   * Executes a series of commands the given command.  Accumulates all the
+   * results of these commands into the answers and messages lists.
+   * @param command The command to execute
+   */
+  void executeCommand(String command) {
+    // Reset answers and messages
+    answers.clear();
+    messages.clear();
+
+    for (String query: commandSplitter.split(command)) {
+
+      if (log.isDebugEnabled()) log.debug("Starting execution of command \"" + command + "\"");
+
+      // execute the command
+      if (!autoTql.executeCommand(query)) {
+        close();
+        return;
+      }
+
+      if (log.isDebugEnabled()) log.debug("Completed execution of commmand \"" + command + "\"");
+
+      Exception e = autoTql.getLastException();
+      if (e != null) log.warn("Couldn't execute command", e);
+
+      // Add the message and answer
+      messages.add(autoTql.getLastMessage());
+
+      Answer answer = autoTql.getLastAnswer();
+      if (answer != null) answers.add(answer);
+    }
+  }
+
+  /**
+   * Executes a script given by URL name. {@see executeScript} for implementation.
+   * @param script The string for the script URL.
+   * @throws MalformedURLException The given script name cannot be represented as a URL.
+   */
+  private void executeScript(String script) throws MalformedURLException {
+    if (script == null) return;
+    executeScript(new URL(script));
+  }
+
+  /**
+   * Executes a script.  This is done separately to {@link org.mulgara.query.operation.ExecuteScript}
+   * as it expects to use a single established connection, while this method will establish new
+   * connections for each line, as appropriate.
+   * @param scriptURL the URL of the script to load. May be <code>null</code> in which
+   *        case nothing will be done.
+   */
+  private void executeScript(URL scriptURL) {
+
+    if (scriptURL == null) return;
+
+    // log that we're executing the script
+    log.debug("Executing script from " + scriptURL);
+
+    // keep a record of the line number
+    int line = 0;
+
+    try {
+
+      // create a reader to read the contents of the script
+      BufferedReader scriptIn = new BufferedReader(new InputStreamReader(scriptURL.openStream()));
+
+      String command;
+      while ((command = scriptIn.readLine()) != null) {
+
+        line++;
+        command = command.trim();
+
+        if (!command.equals("")) {
+          autoTql.executeCommand(command);
+
+          Answer answer = autoTql.getLastAnswer();
+          if (answer != null) {
+            printAnswer(answer, System.out);
+            answer.close();
+          }
+
+          String lastMessage = autoTql.getLastMessage();
+          if ((lastMessage != null) && (lastMessage != "") && (gui != null)) System.out.println(lastMessage);
+        }
+
+      }
+    } catch (TuplesException te) {
+      System.err.println("Error accessing results (line " + line + "): " + te.getMessage());
+      log.warn("Unable to complete script - " + scriptURL + " (line " + line + ") - " + te);
+    } catch (IOException ioe) {
+      System.err.println("Could not execute script (line " + line + "): " + ioe);
+      log.warn("Unable to execute script - " + scriptURL + " (line " + line + ") - " + ioe);
+    }
+  }
+
+
+  /**
+   * Create a UI and start it up.  Returns when the GUI has been exited.
+   */
+  private void runInterface() {
+    // Create the UI.
+    JFrame mainWindow = new JFrame(SHELL_NAME);
+    mainWindow.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
+    mainWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+
+    gui = new TqlSessionUI(this, System.in, System.out);
+    mainWindow.getContentPane().add(gui);
+
+    if (log.isInfoEnabled()) log.info("Starting TQL interpreter");
+
+    motdInitialization();
+
+    // Start the application, by making the UI visible
+    mainWindow.setVisible(true);
+
+    if (log.isInfoEnabled()) log.info("Stopping TQL interpreter");
+    if (log.isDebugEnabled()) log.debug("Executed post-loading script");
+  }
+
+
+  /**
+   * Initiates a session using the given <code>session</code>
+   * @param session the interactive session to issue commands to
+   * @param in the stream to read commands from
+   * @param out the stream to print responses to
+   */
+  private void motdInitialization() {
+    gui.print("TQL Command Line Interface" + EOL);
+    gui.print(EOL + "Type \"help ;\", then enter for help." + EOL + EOL + PS1);
+  }
+
+
+  /**
+   * Returns the location of the script to run.
+   * @return A string with the location of the script to run.
+   */
+  private String getScript() throws MalformedURLException {
+    return scriptLocation;
+  }
+
+
+  /**
+   * @return the URL of the pre-loading script
+   */
+  private URL getPreLoadingScriptURL() {
+    return preLoadingScriptUrl;
+  }
+
+
+  /**
+   * @return the URL of the post-loading script
+   */
+  private URL getPostLoadingScriptURL() {
+    return postLoadingScriptUrl;
+  }
+
+
+  /**
+   * Closes the session associated with this interpreter, and ends the program.
+   * Subclasses that override this method <strong>must</strong> call
+   * <code>super.close()</code>.
+   */
+  private void close() {
+    // Close the session, if any
+    if (autoTql != null) autoTql.close();
+    System.exit(0);
+  }
+
+
+  /**
+   * Locates and sets the default loading scripts.
+   */
+  private void setDefaultLoadingScripts() {
+    preLoadingScriptUrl = locateScript(PRE_LOADING_SCRIPT_PATH);
+    postLoadingScriptUrl = locateScript(POST_LOADING_SCRIPT_PATH);
+  }
+
+
+  /**
+   * <p>Locates the loading script with the given path.</p>
+   * <p>This locates scripts in the following order:</p>
+   * <ol>
+   *   <li> Current working directory;</li>
+   *   <li> System classpath (if embedded in a JAR).</li>
+   * </ol>
+   * <p>Note. These could be overwritten by the command-line options <code>-o</code>
+   * and <code>-p</code>.</p>
+   *
+   * @param scriptPath the path to the script to locate
+   * @return a URL to the script, <code>null</code> if the script could not be found
+   */
+  private URL locateScript(String scriptPath) {
+
+    URL scriptUrl = null;
+
+    // find the current directory
+    String currentDirectory = System.getProperty(USER_DIR);
+
+    // append a "/" if we need to
+    if (!currentDirectory.endsWith("/")) currentDirectory += File.separator;
+
+    log.debug("Looking for script " + scriptPath + " in " + currentDirectory);
+
+    // try to find the script
+    File loadingScript = new File(currentDirectory + scriptPath);
+
+    if (loadingScript.exists() && loadingScript.isFile()) {
+
+      // found the URL. Return it.
+      log.debug("Found loading script - " + loadingScript);
+      try {
+        scriptUrl = loadingScript.toURL();
+      } catch (MalformedURLException mue) {
+        log.warn("Unable to convert loading script filename to URL - " + mue.getMessage());
+        System.err.println("Unable to convert loading script filename " + "to URL - " + loadingScript);
+      }
+
+    } else {
+      log.debug("Looking for loading script " + scriptPath + " in classpath");
+      // try to obtain the URL from the classpath
+      URL loadingScriptUrl = ClassLoader.getSystemResource(scriptPath);
+      if (loadingScriptUrl != null) {
+        log.debug("Found loading script at - " + loadingScriptUrl);
+        scriptUrl = loadingScriptUrl;
+      }
+    }
+
+    return scriptUrl;
+  }
+
+
+  /**
+   * Executes the pre-loading script.
+   * @param loadingScriptUrl the URL of the loading (pre/post) script to execute
+   */
+  private void executeLoadingScript(URL loadingScriptUrl) {
+    if (loadingScriptUrl != null) {
+      log.debug("Executing loading script " + loadingScriptUrl);
+      executeScript(loadingScriptUrl);
+    }
+  }
+
+
+  /**
+   * Processes the command line options passed to the interpreter.
+   * @param parser the command line option parser to use to parse the command line options
+   * @return <code>true</code> if the UI is required, <code>false</code> if the input is a script.
+   */
+  private boolean handleOptions(ItqlOptionParser parser) {
+
+    log.debug("Processing command line options");
+
+    try {
+      // find out if the user wants help
+      if (parser.getOptionValue(ItqlOptionParser.HELP) != null) {
+        printUsage(System.out);
+        return false;  // don't start the UI
+      } else {
+
+        // dump the interpreter configuration
+        if (null != parser.getOptionValue(ItqlOptionParser.DUMP_CONFIG)) dumpConfig();
+
+        // load an external interpreter configuration file
+        String itqlConf = (String)parser.getOptionValue(ItqlOptionParser.ITQL_CONFIG);
+        if (itqlConf != null) loadItqlConfig(new URL(itqlConf));
+
+        // load an external logging configuration file
+        String logConf = (String)parser.getOptionValue(ItqlOptionParser.LOG_CONFIG);
+        if (logConf != null) loadLoggingConfig(new URL((String)logConf));
+
+        // find out whether to execute pre-and post loading scripts
+        if (null == parser.getOptionValue(ItqlOptionParser.NO_LOAD)) {
+
+          // override the default pre-loading script
+          String preScript = (String)parser.getOptionValue(ItqlOptionParser.PRE_SCRIPT);
+          if (preScript != null) preLoadingScriptUrl = new URL(preScript);
+
+          // override the default post-loading script
+          String postScript = (String)parser.getOptionValue(ItqlOptionParser.POST_SCRIPT);
+          if (postScript != null) postLoadingScriptUrl = new URL(preScript);
+
+        } else {
+
+          log.debug("Pre-loading and post-loading scripts disabled");
+          preLoadingScriptUrl = null;
+          postLoadingScriptUrl = null;
+        }
+
+        // If there is a script to run, then return false, else true for no script
+        scriptLocation = (String)parser.getOptionValue(ItqlOptionParser.SCRIPT);
+        return null == scriptLocation;
+      }
+    } catch (MalformedURLException e) {
+      log.warn("Invalid URL on command line - " + e.getMessage());
+      System.err.println("Invalid URL - " + e.getMessage());
+      printUsage(System.out);
+    } catch (Exception e) {
+      log.warn("Could not start interpreter - " + e.getMessage());
+      System.err.println("Error - " + e.getMessage());
+    }
+    // fall through from exception
+    return false;
+  }
+
+
+  /**
+   * Prints the usage instructions for the interpreter.
+   * @param out An output stream to print the instructions to.
+   */
+  private void printUsage(PrintStream out) {
+    // build the usage message
+    StringBuffer usage = new StringBuffer();
+    usage.append("Usage: java -jar <jarfile> ");
+
+    usage.append("[-h|-n] ");
+    usage.append("[-l <url>] ");
+    usage.append("[-o <url>] ");
+    usage.append("[-p <url>] ");
+    usage.append("[-s <url>]");
+    usage.append(EOL).append(EOL);
+
+    usage.append("-h, --help          display this help screen").append(EOL);
+    usage.append("-n, --noload        do not execute pre- and post-loading ");
+    usage.append("scripts (useful with -s)").append(EOL);
+
+    usage.append("-l, --logconfig     use an external logging configuration file").append(EOL);
+    
+    usage.append("-o, --postload      execute an iTQL script after interpreter stops,").append(EOL);
+    usage.append("                    overriding default post-loading script").append(EOL);
+    usage.append("-p, --preload       execute an iTQL script before interpreter starts,").append(EOL);
+    usage.append("                    overriding default pre-loading script").append(EOL);
+    usage.append("-s, --script        execute an iTQL script and quit").append(EOL);
+    usage.append(EOL);
+    usage.append("The intepreter executes default pre- and post-loading scripts. These can be").append(EOL);
+    usage.append("used to load aliases etc. into the interpreter to simplify commands. The").append(EOL);
+    usage.append("default scripts are contained within the JAR file, however you can overide").append(EOL);
+    usage.append("these by placing files named default-pre.itql and default-post.itql in").append(EOL);
+    usage.append("the directory from which you run the interpreter, or by using the -p and").append(EOL);
+    usage.append("-o options.").append(EOL);
+
+    // print the usage
+    out.println(usage.toString());
+  }
+
+
+  /**
+   * Dunps the current interpreter configuration to the current directory. This
+   * will dump the entire interpreter configuration including the logging and
+   * application logging.
+   */
+  private void dumpConfig() {
+    // we don't support this feature yet
+    throw new UnsupportedOperationException();
+  }
+
+
+  /**
+   * Loads an external TQL interpreter configuration file. This will use the
+   * configuration in the file located at <code>itqlConfURL</code>, instead of
+   * the configuration contained within the distribution JAR file.
+   *
+   * @param configUrl the URL of the external iTQL interpreter configuration file
+   * @return <code>true</code> for successful loading of the file.
+   */
+  private boolean loadItqlConfig(URL configUrl) {
+    // we don't support this feature yet
+    throw new UnsupportedOperationException();
+  }
+
+
+  /**
+   * Loads an external XML log4j configuration file. This will use the
+   * configuration in the file located at <code>logConfURL</code>, instead of
+   * the configuration contained within the distribution JAR file.
+   * @param logConfUrl the URL of the external XML log4j configuration file
+   * @throws Exception if unable to complete the method sucessfully
+   */
+  private void loadLoggingConfig(URL logConfUrl) throws Exception {
+    // configure the logging service
+    DOMConfigurator.configure(logConfUrl);
+    log.info("Using new logging configuration from " + logConfUrl);
+  }
+
+
+  /**
+   * Loads the embedded logging configuration (from the JAR file).
+   */
+  private void loadLoggingConfig() {
+    // get a URL from the classloader for the logging configuration
+    URL log4jConfigUrl = ClassLoader.getSystemResource(LOG4J_CONFIG_PATH);
+
+    // if we didn't get a URL, tell the user that something went wrong
+    if (log4jConfigUrl == null) {
+      System.err.println("Unable to find logging configuration file in JAR " +
+          "with " + LOG4J_CONFIG_PATH + ", reverting to default configuration.");
+      BasicConfigurator.configure();
+    } else {
+      try {
+        // configure the logging service
+        DOMConfigurator.configure(log4jConfigUrl);
+        log.info("Using logging configuration from " + log4jConfigUrl);
+      } catch (FactoryConfigurationError e) {
+        System.err.println("Unable to configure logging service");
+      }
+    }
+  }
+
+
+  /**
+   * Prints an answer to a print stream.
+   * @param answer The answer to print
+   * @param out The print stream to send the answer to.
+   * @throws TuplesException There was an error moving through the data in the answer.
+   */
+  private void printAnswer(Answer answer, PrintStream out) throws TuplesException {
+    answer.beforeFirst();
+    if (answer.isUnconstrained()) {
+      out.println("[ true ]");
+    } else {
+      while (answer.next()) {
+        out.print("[ ");
+        for (int index = 0; index < answer.getNumberOfVariables(); index++) {
+          out.print(String.valueOf(answer.getObject(index)));
+          if (index < (answer.getNumberOfVariables() - 1)) out.print(", ");
+        }
+        out.println(" ]");
+      }
+    }
+  }
+
+}

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSessionUI.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/TqlSessionUI.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSessionUI.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/TqlSessionUI.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,777 @@
+/*
+ * The contents of this file are subject to the Mozilla Public License
+ * Version 1.1 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * The Original Code is the Kowari Metadata Store.
+ *
+ * The Initial Developer of the Original Code is Plugged In Software Pty
+ * Ltd (http://www.pisoftware.com, mailto:info at pisoftware.com). Portions
+ * created by Plugged In Software Pty Ltd are Copyright (C) 2001,2002
+ * Plugged In Software Pty Ltd. All Rights Reserved.
+ *
+ * Contributor(s): N/A.
+ *
+ * [NOTE: The text of this Exhibit A may differ slightly from the text
+ * of the notices in the Source Code files of the Original Code. You
+ * should use the text of this Exhibit A rather than the text found in the
+ * Original Code Source Code for Your Modifications.]
+ */
+
+package org.mulgara.itql;
+
+/**
+ * Swing based iTQL session command line shell.
+ *
+ * @created 2004-01-15
+ *
+ * @author Andrew Newman
+ *
+ * @version $Revision: 1.8 $
+ *
+ * @modified $Date: 2005/01/05 04:58:15 $ by $Author: newmana $
+ *
+ * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
+ *
+ * @copyright &copy;2004 <a href="http://www.pisoftware.com/">Plugged In
+ *      Software Pty Ltd</a>
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+import java.util.*;
+import java.util.List;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import javax.swing.*;
+import javax.swing.text.*;
+
+import org.apache.log4j.*;
+import org.jrdf.graph.Node;
+
+import org.mulgara.query.Answer;
+
+ at SuppressWarnings("serial")
+public class TqlSessionUI extends JScrollPane implements Runnable,
+    KeyListener, java.awt.event.MouseListener, ActionListener {
+
+  /** The logging category to log to */
+  private final static Logger log = Logger.getLogger(TqlSessionUI.class);
+  
+  private static final String NEWLINE = System.getProperty("line.separator");
+  
+  /** The bold font used for output */
+  private final Font boldFont = new Font("Monospaced", Font.BOLD, 12);
+  
+  /** The iTQL session to send queries and used to send results. */
+  private TqlSession tqlSession;
+
+  /** Used to pipe input. */
+  private InputStream inPipe;
+
+  /** The list of history items. */
+  private ArrayList<String> history = new ArrayList<String>();
+
+  /** Current index into the history. */
+  private int historyIndex = 0;
+
+  /** Current cursor position. */
+  private int cursorPosition = 0;
+
+  /** The UI widget for displaying all text. */
+  private JTextPane text;
+
+  /** The default styled document. */
+  private DefaultStyledDocument doc;
+
+  /** Popup menu for Windows users. */
+  private JPopupMenu popupMenu = new JPopupMenu();
+
+  /** Whether we are running a command still. */
+  private volatile boolean runningCommand = false;
+
+  /**
+   * Create a new UI representation.
+   * @param newItqlSession the itql session to call when we receive commands and
+   *        when we want to display them.
+   */
+  public TqlSessionUI(TqlSession newTqlSession, InputStream inStream, OutputStream outStream) {
+    super();
+    tqlSession = newTqlSession;
+    doc = new DefaultStyledDocument();
+    text = new PasteablePane(doc);
+    text.setFont(new Font("Monospaced", Font.PLAIN, 12));
+    text.setMargin(new Insets(5, 5, 5, 5));
+    text.addKeyListener(this);
+    text.addMouseListener(this);
+    setViewportView(text);
+
+    // Consume middle click to handle properly for Unix/Linux
+    Toolkit toolkit = Toolkit.getDefaultToolkit();
+    toolkit.addAWTEventListener(new MouseListener(), AWTEvent.MOUSE_EVENT_MASK);
+
+    // Add popup menu for Windows users.
+    JMenuItem copyItem = new JMenuItem("Copy");
+    JMenuItem pasteItem = new JMenuItem("Paste");
+    popupMenu.add(copyItem);
+    popupMenu.add(pasteItem);
+    copyItem.addActionListener(this);
+    pasteItem.addActionListener(this);
+
+    inPipe = inStream;
+
+    // Start the inpipe watcher
+    new Thread(this).start();
+    requestFocus();
+  }
+
+  public void requestFocus() {
+
+    super.requestFocus();
+    text.requestFocus();
+  }
+
+  /**
+   * Handle key pressed event.
+   *
+   * @param e the key that was pressed.
+   */
+  public void keyPressed(KeyEvent e) {
+
+    switch (e.getKeyCode()) {
+
+      // Enter pressed
+      case (KeyEvent.VK_ENTER):
+
+        if (e.getID() == KeyEvent.KEY_PRESSED) {
+
+          if (!runningCommand) {
+
+            enterPressed();
+            cursorPosition = textLength();
+            text.setCaretPosition(cursorPosition);
+          }
+        }
+        e.consume();
+        text.repaint();
+      break;
+
+      // Up history
+      case (KeyEvent.VK_UP):
+
+        if (e.getID() == KeyEvent.KEY_PRESSED) {
+
+          historyUp();
+        }
+        e.consume();
+      break;
+
+      // Down history
+      case (KeyEvent.VK_DOWN):
+        if (e.getID() == KeyEvent.KEY_PRESSED) {
+
+          historyDown();
+        }
+        e.consume();
+      break;
+
+      // Left or delete.
+      case (KeyEvent.VK_LEFT):
+      case (KeyEvent.VK_DELETE):
+
+        if (text.getCaretPosition() <= cursorPosition) {
+
+          e.consume();
+        }
+      break;
+
+      // Go right.
+      case (KeyEvent.VK_RIGHT):
+
+        if (text.getCaretPosition() < cursorPosition) {
+
+          // move caret first!
+        }
+        text.repaint();
+      break;
+
+      // Control-A go to start of line.
+      case (KeyEvent.VK_A):
+
+        if ((e.getModifiers() & InputEvent.CTRL_MASK) > 0) {
+
+          text.setCaretPosition(cursorPosition);
+          e.consume();
+        }
+      break;
+
+      // Control-C copy the text.
+      case (KeyEvent.VK_C):
+
+        if (text.getSelectedText() == null) {
+
+          text.copy();
+          e.consume();
+        }
+      break;
+
+
+      // Control-E go to end of line.
+      case (KeyEvent.VK_E):
+
+        if ((e.getModifiers() & InputEvent.CTRL_MASK) > 0) {
+
+          text.setCaretPosition(textLength());
+          e.consume();
+        }
+      break;
+
+      // Control-U remove line
+      case (KeyEvent.VK_U):
+
+        if ((e.getModifiers() & InputEvent.CTRL_MASK) > 0) {
+
+          replaceText("", cursorPosition, textLength());
+          historyIndex = 0;
+          e.consume();
+        }
+      break;
+
+      // Home go to start of line
+      case (KeyEvent.VK_HOME):
+
+        text.setCaretPosition(cursorPosition);
+        e.consume();
+      break;
+
+      // Go to end of line
+      case (KeyEvent.VK_END):
+
+        text.setCaretPosition(textLength());
+        e.consume();
+      break;
+
+      // Ignore modifiers
+      case (KeyEvent.VK_ALT):
+      case (KeyEvent.VK_CAPS_LOCK):
+      case (KeyEvent.VK_CONTROL):
+      case (KeyEvent.VK_ESCAPE):
+      case (KeyEvent.VK_F1):
+      case (KeyEvent.VK_F2):
+      case (KeyEvent.VK_F3):
+      case (KeyEvent.VK_F4):
+      case (KeyEvent.VK_F5):
+      case (KeyEvent.VK_F6):
+      case (KeyEvent.VK_F7):
+      case (KeyEvent.VK_F8):
+      case (KeyEvent.VK_F9):
+      case (KeyEvent.VK_F10):
+      case (KeyEvent.VK_F11):
+      case (KeyEvent.VK_F12):
+      case (KeyEvent.VK_INSERT):
+      case (KeyEvent.VK_META):
+      case (KeyEvent.VK_PAUSE):
+      case (KeyEvent.VK_PRINTSCREEN):
+      case (KeyEvent.VK_SHIFT):
+      case (KeyEvent.VK_SCROLL_LOCK):
+
+        // Do nothing.
+
+      break;
+
+      // Handle normal characters
+      default:
+
+        if ( (e.getModifiers() & (InputEvent.ALT_MASK | InputEvent.CTRL_MASK |
+            InputEvent.META_MASK)) == 0) {
+
+          if (text.getCaretPosition() < cursorPosition) {
+
+            text.setCaretPosition(textLength());
+          }
+          text.repaint();
+        }
+
+        // Handle back space - don't let it go too far back.
+        if (e.paramString().indexOf("Backspace") != -1) {
+
+          if (text.getCaretPosition() <= cursorPosition) {
+
+            e.consume();
+            break;
+          }
+        }
+      break;
+    }
+  }
+
+  public void keyTyped(KeyEvent e) {
+
+    if (e.paramString().indexOf("Backspace") != -1) {
+
+      if (text.getCaretPosition() <= cursorPosition) {
+
+        e.consume();
+      }
+    }
+  }
+
+  public void keyReleased(KeyEvent e) {
+
+    // Do nothing.
+  }
+
+  public void mouseClicked(MouseEvent e) {
+
+    // Do nothing.
+  }
+
+  public void mouseEntered(MouseEvent e) {
+
+    // Do nothing.
+  }
+
+  public void mouseExited(MouseEvent e) {
+
+    // Do nothing.
+  }
+
+  public void mousePressed(MouseEvent e) {
+
+    if (e.isPopupTrigger()) {
+
+      popupMenu.show(e.getComponent(), e.getX(), e.getY());
+    }
+  }
+
+  public void mouseReleased(MouseEvent e) {
+
+    if (e.isPopupTrigger()) {
+
+      popupMenu.show(e.getComponent(), e.getX(), e.getY());
+    }
+  }
+
+  public void actionPerformed(ActionEvent event) {
+
+    String eventOccurred = event.getActionCommand();
+
+    if (eventOccurred.equals("Copy")) {
+
+      text.copy();
+    } else if (eventOccurred.equals("Paste")) {
+
+      text.paste();
+    }
+  }
+
+  /**
+   * Returns the length of the current text buffer.
+   *
+   * @return length of the current text buffer.
+   */
+  private int textLength() {
+    return text.getDocument().getLength();
+  }
+
+  /**
+   * Replaces the given string to a position in the currently displayed line.
+   *
+   * @param newString the string to add.
+   * @param start the starting position.
+   * @param end the end position.
+   */
+  private void replaceText(String newString, int start, int end) {
+    text.select(start, end);
+    text.replaceSelection(newString);
+  }
+
+  /**
+   * When the enter key has been pressed process the current command.
+   */
+  private void enterPressed() {
+    String command = getCommand();
+
+    // Create null command.
+    if (command.length() != 0) {
+      // Put the command at the end of the array.
+      history.add(command);
+      command = command + NEWLINE;
+
+      // If the array gets too large remove the last entry.
+      if (history.size() > 30) history.remove(0);
+      
+      // Indicate that we are running a command.
+      runningCommand = true;
+
+      // Create a new thread and start it.
+      ExecutionThread execThread = new ExecutionThread("execThread", command);
+      execThread.start();
+    } else {
+      // We've just hit enter so print the prompt.
+      printPrompt();
+    }
+  }
+
+  /**
+   * Prints out the prompt.
+   */
+  public void printPrompt() {
+    print(NEWLINE + TqlSession.PROMPT);
+    historyIndex = 0;
+    text.repaint();
+  }
+
+  /**
+   * Returns the current command.
+   *
+   * @return the current command.
+   */
+  private String getCommand() {
+    String command = "";
+    try {
+      command = text.getText(cursorPosition, textLength() - cursorPosition);
+    } catch (BadLocationException e) {
+      log.error("Failed to get text command at position: " + cursorPosition, e);
+    }
+    return command;
+  }
+
+  /**
+   * Display the next command in the history buffer.
+   */
+  private void historyUp() {
+    // Ensure there's a history and that the index never goes above the array size.
+    if ((history.size() != 0) && (historyIndex != history.size())) {
+      historyIndex++;
+      displayHistoryLine();
+    }
+  }
+
+  /**
+   * Display the previous command in the history buffer.
+   */
+  private void historyDown() {
+
+    // Ensure there's a history and that the index is initially above 1.
+    if ((history.size() != 0) && (historyIndex > 1)) {
+
+      historyIndex--;
+      displayHistoryLine();
+    }
+  }
+
+  /**
+   * Displays the history line to the screen.
+   */
+  private void displayHistoryLine() {
+    String showline = (String) history.get(history.size() - historyIndex);
+    replaceText(showline, cursorPosition, textLength());
+    text.setCaretPosition(textLength());
+    text.repaint();
+  }
+
+  /**
+   * Prints a message to the UI with a line separator.
+   *
+   * @param message the message to display.
+   */
+  public void println(String message) {
+    print(message + NEWLINE);
+    text.repaint();
+  }
+
+  /**
+   * Prints empty line.
+   */
+  public void println() {
+    print(NEWLINE);
+    text.repaint();
+  }
+
+  /**
+   * Prints a message to the UI. Sends a little "closure" to the UI thread.
+   * @param message the message to display.
+   */
+  public void print(final String message) {
+    invokeAndWait(new Runnable() {
+      public void run() {
+        append(message);
+        cursorPosition = textLength();
+        text.setCaretPosition(cursorPosition);
+      }
+    });
+  }
+
+
+  /**
+   * Adds a text to the UI. Sends a little "closure" to the UI thread.
+   * @param message the message to display.
+   */
+  public void injectCommand(final String cmd) {
+    invokeAndWait(new Runnable() {
+      public void run() {
+        append(cmd);
+        text.setCaretPosition(cursorPosition);
+        if (cmd.endsWith(";") || cmd.endsWith("\n")) enterPressed();
+      }
+    });
+  }
+
+
+  /**
+   * Print out an error message to the UI.
+   * @param errorMessage the error message to display.
+   */
+  public void error(String errorMessage) {
+    print(errorMessage, Color.red);
+  }
+
+
+  /**
+   * Print out the message with the given color using the current font.
+   * @param message the message to display.
+   * @param color the color to use.
+   */
+  public void print(String message, Color color) {
+    print(message, null, color);
+  }
+
+
+  /**
+   * Print out the message with the given font and colour.
+   * Uses invoke and wait to send a "closure" to the UI thread.
+   * @param message the message to display.
+   * @param font the font to use.
+   * @param color the color to use.
+   */
+  public void print(final String message, final Font font, final Color color) {
+    invokeAndWait(new Runnable() {
+      public void run() {
+        try {
+          AttributeSet oldStyle = text.getCharacterAttributes();
+          setStyle(font, color);
+          append(message);
+          cursorPosition = textLength();
+          text.setCaretPosition(cursorPosition);
+          text.setCharacterAttributes(oldStyle, true);
+        } catch (Exception e) {
+          log.error("Error when printing: " + message, e);
+        }
+      }
+    });
+  }
+
+
+  /**
+   * Print out the message followed by a newline with the given font and colour.
+   * @param message the message to display.
+   * @param font the font to use.
+   * @param color the color to use.
+   */
+  public void println(final String message, final Font font, final Color color) {
+    print(message + NEWLINE, font, color);
+    text.repaint();
+  }
+
+
+  /**
+   * Sets the new style of a font and color to the text.
+   * @param font the new font.
+   * @param color the new color.
+   * @return the attributes of the given font and color.
+   */
+  private AttributeSet setStyle(Font font, Color color) {
+    MutableAttributeSet attr = new SimpleAttributeSet();
+    StyleConstants.setForeground(attr, color);
+    // Don't set if null
+    if (font != null) {
+      StyleConstants.setBold(attr, font.isBold());
+      StyleConstants.setFontFamily(attr, font.getFamily());
+      StyleConstants.setFontSize(attr, font.getSize());
+    }
+    text.setCharacterAttributes(attr, false);
+    return text.getCharacterAttributes();
+  }
+
+
+  /**
+   * Append the given string to the existing string.
+   * @param newString the string to append to.
+   */
+  private void append(String newString) {
+    int length = textLength();
+    text.select(length, length);
+    text.replaceSelection(newString);
+  }
+
+
+  /**
+   * Thread that reads the inPipe, and prints the output.
+   */
+  public void run() {
+    try {
+      byte[] buffer = new byte[255];
+      int read;
+      log.info("Starting input reader");
+      while ((read = inPipe.read(buffer)) != -1) {
+        injectCommand(new String(buffer, 0, read));
+      }
+    } catch (IOException e) {
+      log.error("Error reading input", e);
+    }
+    log.warn("End of input");
+  }
+
+
+  /**
+   * If not in the event thread run via SwingUtilities.invokeAndWait().
+   * @param runnable The operation that a client wants the UI to perform. Like a "closure".
+   */
+  private void invokeAndWait(Runnable runnable) {
+    if (!SwingUtilities.isEventDispatchThread()) {
+      try {
+        SwingUtilities.invokeAndWait(runnable);
+      } catch (Exception e) {
+        log.error("Error while executing invoke and wait", e);
+      }
+    } else {
+      runnable.run();
+    }
+  }
+
+
+  /**
+   * Extension to JTextPane to put all pastes at the end of the command line.
+   */
+  class PasteablePane extends JTextPane {
+
+    public PasteablePane(StyledDocument doc) {
+      super(doc);
+    }
+
+    public void paste() {
+      super.paste();
+    }
+  }
+
+  /** Class to listen for mouse press events. */
+  class MouseListener implements AWTEventListener {
+    public void eventDispatched(AWTEvent event) {
+      MouseEvent me = (MouseEvent)event;
+      if (me.getButton() == MouseEvent.BUTTON2) me.consume();
+    }
+  }
+
+
+  /**
+   * Executes the command in a separate thread and display the results.
+   */
+  class ExecutionThread extends Thread {
+
+    /** The command to execute. */
+    private String command;
+
+    /**
+     * Create a new execution thread.
+     * @param threadName the name of the thread.
+     * @param newCommand the iTQL command to execute.
+     */
+    public ExecutionThread(String threadName, String newCommand) {
+      super(threadName);
+      command = newCommand;
+    }
+
+
+    /**
+     * Run the command and display answer results.
+     */
+    public void run() {
+      tqlSession.executeCommand(command);
+      println();
+
+      List<Answer> answers = tqlSession.getLastAnswers();
+      List<String> messages = tqlSession.getLastMessages();
+
+      if (answers.isEmpty()) {
+        for (String message: messages) println(message, boldFont, Color.BLACK);
+      } else {
+        int answerIndex = 0;
+        while (answerIndex < answers.size()) {
+          String lastMessage = (String)messages.get(answerIndex);
+          try {
+            // Assume the same number of answers and messages
+            Answer answer = answers.get(answerIndex);
+  
+            // If there's more than one answer print a heading.
+            if (answers.size() > 1) {
+              println();
+              // If there's more than one answer add an extra line before the heading.
+              println("Executing Query " + (answerIndex+1), boldFont, Color.BLACK);
+            }
+  
+            // print the results
+            if (answer != null) {
+              boolean hasAnswers = true;
+  
+              long rowCount = 0;
+              answer.beforeFirst();
+              if (answer.isUnconstrained()) {
+                println("[ true ]");
+                rowCount = 1;
+              } else {
+                if (!answer.next()) {
+                  print("No results returned.", boldFont, Color.BLACK);
+                  hasAnswers = false;
+                } else {
+                  do {
+                    rowCount++;
+                    print("[ ");
+                    for (int index = 0; index < answer.getNumberOfVariables(); index++) {
+                      Object object = answer.getObject(index);
+                      assert(object instanceof Answer) ||
+                            (object instanceof Node  ) ||
+                            (object == null);
+                      print(String.valueOf(object));
+                      if (index < (answer.getNumberOfVariables() - 1)) print(", ");
+                    }
+                    println(" ]");
+                  } while (answer.next());
+                }
+              }
+              if (hasAnswers) println(rowCount + " rows returned.", boldFont, Color.BLACK);
+              answer.close();
+            }
+          } catch (Exception te) {
+            // Failed to iterate over or retrieve the answer.
+            log.fatal("Failed to retrieve or iterate over answer", te);
+            error("Failed to get answer");
+          }
+  
+          if ((lastMessage != null) && (lastMessage != "")) print(lastMessage, boldFont, Color.BLACK);
+  
+          // If there's more than one answer add a new line.
+          if (answers.size() > 1)  println();
+  
+          // Increment index
+          answerIndex++;
+        }
+      }
+
+      // Signal that the command has finished and display prompt
+      runningCommand = false;
+      printPrompt();
+    }
+  }
+  
+}

Copied: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/URIUtil.java (from rev 619, trunk/src/jar/itql/java/org/mulgara/itql/URIUtil.java)
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/URIUtil.java	                        (rev 0)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/URIUtil.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,51 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.itql;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Map;
+
+/**
+ * A set of methods for managing common URI operations.
+ *
+ * @created 2007-08-09
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class URIUtil {
+
+  /**
+   * Replace an alias in a URI, if one is recognized.
+   * @param uriString A string with the initial uri to check for aliases.
+   * @param aliasMap The map of known aliases to the associated URIs
+   * @return A new URI with the alias replaced, or the original if no alias is found.
+   */
+  public static URI convertToURI(String uriString, Map<String,URI> aliasMap) {
+    try {
+      URI uri = new URI(uriString);
+      if (uri.isOpaque()) {
+        // Attempt qname-to-URI substitution for aliased namespace prefixes
+        URI mapping = aliasMap.get(uri.getScheme());
+        if (mapping != null) {
+          uri = new URI(mapping + uri.getSchemeSpecificPart());
+        }
+      }
+      return uri;
+    } catch (URISyntaxException e) {
+      throw new Error("Bad URI syntax in resource: " + e);
+    }
+  }
+  
+}

Modified: branches/mgr-73/src/jar/itql/java/org/mulgara/itql/VariableBuilder.java
===================================================================
--- branches/mgr-73/src/jar/itql/java/org/mulgara/itql/VariableBuilder.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/java/org/mulgara/itql/VariableBuilder.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -53,10 +53,6 @@
  *
  * @author Andrew Newman
  *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:15 $ by $Author: newmana $
- *
  * @company <a href="mailto:info at PIsoftware.com">Plugged In Software</a>
  *
  * @copyright &copy;2004 <a href="http://www.pisoftware.com/">Plugged In
@@ -66,165 +62,135 @@
  */
 public class VariableBuilder extends AnalysisAdapter {
 
-  /**
-   * The logger
-   */
-  private final static Logger logger =
-      Logger.getLogger(VariableBuilder.class.getName());
+  /** The logger */
+  private final static Logger logger = Logger.getLogger(VariableBuilder.class.getName());
 
-  /**
-   * Variable name generator for anonymous columns
-   */
+  /** Variable name generator for anonymous columns */
   private VariableFactory variableFactory;
 
-  /**
-   * URI Syntax Exception - not null if exception occurred since last get.
-   */
+  /** URI Syntax Exception - not null if exception occurred since last get. */
   private URISyntaxException uriException = null;
 
-  /**
-   * Query Exception - not null if exception occurred since last get.
-   */
+  /** Query Exception - not null if exception occurred since last get. */
   private QueryException queryException = null;
 
   /**
-   * The list of variables
+   * The list of variables - these are mixed object types:
+   * ConstantValue, Variable, Count, SubQuery
    */
-  private List variableList;
+  private List<SelectElement> variableList;
 
-  /**
-   * The iTQL interpreter
-   */
-  private ItqlInterpreter interpreter;
+  /** The TQL interpreter */
+  private SableCCInterpreter interpreter;
 
+
   /**
    * Create a new builder.  Requires methods on the interpreter in order to
    * function correctly.
-   *
    * @param newInterpreter the interpreter to use.
    */
-  public VariableBuilder(ItqlInterpreter newInterpreter,
-      VariableFactory newVariableFactory) {
-
-    variableList = new ArrayList();
+  public VariableBuilder(SableCCInterpreter newInterpreter, VariableFactory newVariableFactory) {
+    variableList = new ArrayList<SelectElement>();
     interpreter = newInterpreter;
     variableFactory = newVariableFactory;
   }
 
+
   /**
    * Converts a literal element to a constant and adds it to the variable list.
-   *
+   * This method is called back from SableCC.
    * @param element the literal element to add to the variable list.
    */
   public void caseALiteralElement(ALiteralElement element) {
-
     variableList.add(new ConstantValue(
       variableFactory.newVariable(),
-      interpreter.toLiteralImpl(((ALiteralElement) element).getLiteral())
+      interpreter.toLiteralImpl(((ALiteralElement)element).getLiteral())
     ));
   }
 
+
   /**
    * Converts a resource element to a constant and adds it to the variable list.
-   *
+   * This method is called back from SableCC.
    * @param element the resource element to add to the variable list.
    */
   public void caseAResourceElement(AResourceElement element) {
-
     // add a new resource to the list
     variableList.add(new ConstantValue(
       variableFactory.newVariable(),
-      new URIReferenceImpl(interpreter.toURI(
-        ((AResourceElement) element).getResource()
-      ))
+      new URIReferenceImpl(interpreter.toURI(((AResourceElement) element).getResource()))
     ));
   }
 
+
   /**
-   * Gets the string values of a variable element and adds it to the variable
-   * list.
-   *
+   * Gets the string values of a variable element and adds it to the variable list.
+   * This method is called back from SableCC.
    * @param element the variable element to add to the variable list.
    */
   public void caseAVariableElement(AVariableElement element) {
-
     // get the name of this variable
-    String variableName =
-        ((AVariable) ((AVariableElement) element).getVariable()).
-        getIdentifier().getText();
+    String variableName = ((AVariable)((AVariableElement)element).getVariable()).getIdentifier().getText();
 
-    // log that we've found a variable
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found variable $" + variableName);
-    }
+    if (logger.isDebugEnabled()) logger.debug("Found variable $" + variableName);
 
     // add a new variable to the list
     variableList.add(new Variable(variableName));
 
-    if (logger.isDebugEnabled()) {
-      logger.debug("Variable list: " + variableList);
-    }
+    if (logger.isDebugEnabled()) logger.debug("Variable list: " + variableList);
   }
 
+
   /**
    * Handle an aggregate element.  At the moment it handles both count and
-   * sub-queries.  Will set URIException or QueryException if
-   * an exception occurs.
-   *
+   * sub-queries.  Any further aggregates will be instantiated here.
+   * Will set URIException or QueryException if an exception occurs.
+   * This method is called back from SableCC.
    * @param element the aggregate element to add to the variable list.
    */
   public void caseAAggregateElement(AAggregateElement element) {
-
     try {
-      AAggregateElement aggregateElement = (AAggregateElement) element;
-      PAggregate aggregate = aggregateElement.getAggregate();
+      AAggregateElement aggregateElement = (AAggregateElement)element;
 
+      // build the elements of the aggregate
+      Variable aggregateVariable = variableFactory.newVariable();
+      Query aggregateQuery = interpreter.buildQuery(aggregateElement.getQuery());
+      
+      // create the correct aggregate type - count or subquery
+      PAggregate aggregate = aggregateElement.getAggregate();
       if (aggregate instanceof ACountAggregate) {
-        variableList.add(new Count(variableFactory.newVariable(),
-            interpreter.buildQuery(aggregateElement.getQuery())));
+        variableList.add(new Count(aggregateVariable, aggregateQuery));
+      } else if (aggregate instanceof ASubqueryAggregate) {
+        variableList.add(new Subquery(aggregateVariable, aggregateQuery));
+      } else {
+        throw new Error("Unsupported aggregate type: " + aggregate.getClass());
       }
-      else if (aggregate instanceof ASubqueryAggregate) {
-        variableList.add(new Subquery(variableFactory.newVariable(),
-            interpreter.buildQuery(aggregateElement.getQuery())));
-      }
-      else {
-        throw new Error("Unsupported aggregate type: " +
-            aggregate.getClass());
-      }
-    }
-    catch (QueryException qe) {
+    } catch (QueryException qe) {
       queryException = qe;
-    }
-    catch (URISyntaxException use) {
+    } catch (URISyntaxException use) {
       uriException = use;
     }
   }
 
+
   /**
    * Returns the latest variable list or throws an exception if there
    * was an error creating it.  Once called the variable list is cleared
    * and exceptions are nulled.
-   *
+   * @return A list of: Variable, ConstantValue, Count, Subquery.
    * @throws QueryException if the variable does not is invalid
    * @throws URISyntaxException if the variable contains a resource whose
    *   text violates <a href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
    */
-  public List getVariableList() throws QueryException, URISyntaxException {
-
+  public List<SelectElement> getVariableList() throws QueryException, URISyntaxException {
     try {
-      List tmpVariableList = new ArrayList(variableList);
+      List<SelectElement> tmpVariableList = new ArrayList<SelectElement>(variableList);
 
-      if (uriException != null) {
-        throw uriException;
-      }
-      else if (queryException != null) {
-        throw queryException;
-      }
-      else {
-        return tmpVariableList;
-      }
-    }
-    finally {
+      if (uriException != null) throw uriException;
+      else if (queryException != null) throw queryException;
+      else return tmpVariableList;
+
+    } finally {
       uriException = null;
       queryException = null;
       variableList.clear();

Modified: branches/mgr-73/src/jar/itql/sablecc/itql.grammar
===================================================================
--- branches/mgr-73/src/jar/itql/sablecc/itql.grammar	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/itql/sablecc/itql.grammar	2008-01-14 07:33:14 UTC (rev 622)
@@ -24,7 +24,8 @@
   esc,  /* escaping character in quoted literal with '\' */
   lit,  /* quoted literal */
   res,  /* tagged resource */
-  var;  /* escaping variable name with '$' */
+  var,  /* escaping variable name with '$' */
+  lng;  /* language code */
 
 Tokens
   {def}                alias       = 'alias';
@@ -91,9 +92,11 @@
   {def->res}           url        = '<';
   {res->def}           endurl     = '>';
   {def}                datatypeprefix = '^^';
-  {def->var}           variableprefix = '$';
+  {def->lng}           languageprefix = '@';
+  {def->var}           variableprefix = ('$' | '?');
   {def}                number     = digit+;
   {def}                float      = digit+ ('.' digit*) | ('.' digit+);
+  {lng->def}           langid      = letter letter | letter letter '-' letter letter;
 
   {res}                resource    = urlchar*;
   {def->lit, lit->def} quote       = 39;  /* ' */
@@ -300,7 +303,7 @@
     {subquery} subquery ;
 
   literal =
-    [opening]:quote strand* [closing]:quote datatype?;
+    [opening]:quote strand* [closing]:quote language? datatype?;
 
   strand =
     {unescaped} text |
@@ -309,6 +312,9 @@
   datatype =
     datatypeprefix resource;
 
+  language =
+    languageprefix langid;
+
   variable =
     variableprefix identifier;
 

Modified: branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFGraphUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFGraphUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFGraphUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -305,7 +305,7 @@
    */
   private void createModel(URI modelURI) throws Exception {
 
-    this.session.createModel(modelURI, Session.MULGARA_MODEL_URI);
+    this.session.createModel(modelURI, Session.MULGARA_GRAPH_URI);
   }
 
   /**

Modified: branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFLocalGraphUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFLocalGraphUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/jrdf/java/org/mulgara/jrdf/JRDFLocalGraphUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -220,7 +220,7 @@
    */
   private void createModel(URI modelURI) throws Exception {
 
-    this.session.createModel(modelURI, Session.MULGARA_MODEL_URI);
+    this.session.createModel(modelURI, Session.MULGARA_GRAPH_URI);
   }
 
   /**

Modified: branches/mgr-73/src/jar/krule/java/org/mulgara/krule/KruleLoader.java
===================================================================
--- branches/mgr-73/src/jar/krule/java/org/mulgara/krule/KruleLoader.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/krule/java/org/mulgara/krule/KruleLoader.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -69,7 +69,7 @@
   private Session session;
 
   /** The interpreter for parsing queries. */
-  private ItqlInterpreter interpreter;
+  private TqlInterpreter interpreter;
 
   /** The rules. */
   private RuleStructure rules;
@@ -87,19 +87,19 @@
   private String prefixModel;
 
   /** A map of namespace names to the URIs. */
-  private Map aliases;
+  private Map<String,URI> aliases;
 
   /** Map of krule:URIReference nodes to their associated URIs. */
-  private Map uriReferences;
+  private Map<URIReference,URIReference> uriReferences;
 
   /** Map of krule:Variable nodes to their associated nodes. */
-  private Map varReferences;
+  private Map<URIReference,Variable> varReferences;
 
   /** Map of krule:Literal nodes to their associated strings. */
-  private Map literalReferences;
+  private Map<Node,Literal> literalReferences;
 
   /** Map of Constraint nodes to the associated constraint object. */
-  private Map constraintMap;
+  private Map<Node,ConstraintExpression> constraintMap;
 
   /** URI for the Krule namespace. */
   private static final String KRULE = "http://mulgara.org/owl/krule/#";
@@ -211,7 +211,7 @@
     newAliases();
 
     // initialize the constriant map
-    constraintMap = new HashMap();
+    constraintMap = new HashMap<Node,ConstraintExpression>();
   }
 
 
@@ -241,7 +241,7 @@
     this.systemModel = systemModel;
 
     // get a new interpreter
-    interpreter = new ItqlInterpreter(session, aliases);
+    interpreter = new TqlInterpreter(aliases);
 
     rules = null;
     try {
@@ -400,9 +400,9 @@
   private void loadQueries() throws TuplesException, QueryException, KruleStructureException, InitializerException {
     logger.debug("Loading Queries");
     // go through the rules to set their queries
-    Iterator ri = rules.getRuleIterator();
+    Iterator<Rule> ri = rules.getRuleIterator();
     while (ri.hasNext()) {
-      Rule rule = (Rule)ri.next();
+      Rule rule = ri.next();
 
       logger.debug("Reading query for rule: " + rule.getName());
       Query query;
@@ -498,7 +498,7 @@
    * @throws KruleStructureException When there is an error in the RDF data structure.
    * @throws InitializerException When there is an intialization error.
    */
-  private Set findAxioms() throws TuplesException, QueryException, KruleStructureException, InitializerException {
+  private Set<org.jrdf.graph.Triple> findAxioms() throws TuplesException, QueryException, KruleStructureException, InitializerException {
     logger.debug("Loading Axioms");
 
     Query query;
@@ -513,7 +513,7 @@
     Answer answer = session.query(query);
 
     // prepare the set of axioms
-    Set axioms = new HashSet();
+    Set<org.jrdf.graph.Triple> axioms = new HashSet<org.jrdf.graph.Triple>();
 
     try {
       Node sn = null;
@@ -557,8 +557,8 @@
    *
    * @return A map of aliases to their fully qualified names
    */
-  private Map newAliases() {
-    aliases = new HashMap();
+  private Map<String,URI> newAliases() {
+    aliases = new HashMap<String,URI>();
     try {
       aliases.put("rdf", new URI("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
       aliases.put("rdfs", new URI("http://www.w3.org/2000/01/rdf-schema#"));
@@ -631,7 +631,7 @@
     logger.debug("Found all URI references.");
 
     // create the mapping
-    uriReferences = new HashMap();
+    uriReferences = new HashMap<URIReference,URIReference>();
     // map each reference to the associated URI
     try {
       while (answer.next()) {
@@ -670,7 +670,7 @@
     logger.debug("Found all variable references.");
 
     // create the mapping
-    varReferences = new HashMap();
+    varReferences = new HashMap<URIReference,Variable>();
     try {
       // map each reference to the associated variable
       while (answer.next()) {
@@ -709,7 +709,7 @@
     logger.debug("Found all Literals.");
 
     // create the mapping
-    literalReferences = new HashMap();
+    literalReferences = new HashMap<Node,Literal>();
     try {
       // map each reference to the associated String
       while (answer.next()) {
@@ -750,7 +750,7 @@
     logger.debug("Found all simple constraints.");
 
     // create a mapping of URIs to simple constraint structures
-    Map simpleConstraints = new HashMap();
+    Map<Node,Map<Node,Node>> simpleConstraints = new HashMap<Node,Map<Node,Node>>();
     try {
       // map each reference to the associated property/values
       while (answer.next()) {
@@ -767,19 +767,17 @@
     logger.debug("Mapped all constraints to their property/values");
 
     // collect all property/values together into constraints
-    Iterator entries = simpleConstraints.entrySet().iterator();
-    while (entries.hasNext()) {
-      Map.Entry entry = (Map.Entry)entries.next();
+    for (Map.Entry<Node,Map<Node,Node>> entry: simpleConstraints.entrySet()) {
       // get the node in question
-      Node constraintNode = (Node)entry.getKey();
+      Node constraintNode = entry.getKey();
       // get its properties
-      Map pv = (Map)entry.getValue();
+      Map<Node,Node> pv = entry.getValue();
       // get the individual properties
-      ConstraintElement s = convertToElement((Node)pv.get(HAS_SUBJECT));
-      ConstraintElement p = convertToElement((Node)pv.get(HAS_PREDICATE));
-      ConstraintElement o = convertToElement((Node)pv.get(HAS_OBJECT));
+      ConstraintElement s = convertToElement(pv.get(HAS_SUBJECT));
+      ConstraintElement p = convertToElement(pv.get(HAS_PREDICATE));
+      ConstraintElement o = convertToElement(pv.get(HAS_OBJECT));
       // check if there is a "from" property
-      Node from = (Node)pv.get(HAS_MODEL);
+      Node from = pv.get(HAS_MODEL);
       // build the appropriate constraint
       // add it to the map
       if (from == null) {
@@ -820,10 +818,10 @@
     // accumulate all the constraint links and types
 
     // create a map of join constraints to the constraints that they join
-    Map constraintLinks = new HashMap();
+    Map<Node,Set<Node>> constraintLinks = new HashMap<Node,Set<Node>>();
 
     // map the join constraints to the type of join
-    Map joinTypes = new HashMap();
+    Map<Node,URIReference> joinTypes = new HashMap<Node,URIReference>();
 
     try {
       // map each reference to the associated argument and type
@@ -843,24 +841,21 @@
 
     logger.debug("mapping join constraint RDF nodes to join constraint objects");
     // collect all arguments together into constraints and map the node to the constraint
-    Iterator entries = constraintLinks.entrySet().iterator();
-    while (entries.hasNext()) {
-    	  // work with constraint/argument-set pair
-      Map.Entry entry = (Map.Entry)entries.next();
+    for (Map.Entry<Node,Set<Node>> entry: constraintLinks.entrySet()) {
       // get the constraint node in question
-      Node constraintNode = (Node)entry.getKey();
+      Node constraintNode = entry.getKey();
       // see if it maps to a constraint
       if (constraintMap.get(constraintNode) == null) {
         // the constraint does not exist
         // get the argument nodes
-        Set args = (Set)entry.getValue();
+        Set<Node> args = entry.getValue();
         // get the constraint's type
-        Node type = (Node)joinTypes.get(constraintNode);
+        Node type = joinTypes.get(constraintNode);
         if (type == null) {
         	  throw new KruleStructureException("No type available on join constraint");
         }
         // convert the RDF nodes to constraints
-        List constraintArgs = getConstraints(args, constraintLinks, joinTypes);
+        List<ConstraintExpression> constraintArgs = getConstraints(args, constraintLinks, joinTypes);
         ConstraintExpression joinConstraint = newJoinConstraint(type, constraintArgs);
         logger.debug("mapped " + constraintNode + " -> " + joinConstraint);
         // build the join constraint, and map the node to it
@@ -930,7 +925,7 @@
     logger.debug("Retrieved all transitive constraints.");
 
     // set up a mapping of constraints to predicate/SimpleConstraint pairs
-    Map transMap = new HashMap();
+    Map<Node,Map<Node,Node>> transMap = new HashMap<Node,Map<Node,Node>>();
 
     try {
       // accumulate the transitive arguments
@@ -947,15 +942,13 @@
     logger.debug("Mapped all transitive properties");
 
     // build a new transconstraint for each transitive constraint node
-    Iterator it = transMap.entrySet().iterator();
-    while (it.hasNext()) {
-      Map.Entry tEntry = (Map.Entry)it.next();
-      Node constraintNode = (Node)tEntry.getKey();
-      Map arguments = (Map)tEntry.getValue();
+    for (Map.Entry<Node,Map<Node,Node>> tEntry: transMap.entrySet()) {
+      Node constraintNode = tEntry.getKey();
+      Map<Node,Node> arguments = tEntry.getValue();
       Constraint constraint;
       // build the constraint based on the arguments
       if (arguments.size() == 1) {
-        Node sc = (Node)arguments.get(TRANSITIVE_ARGUMENT);
+        Node sc = arguments.get(TRANSITIVE_ARGUMENT);
         if (sc == null) {
           throw new KruleStructureException("Transitive argument not correct");
         }
@@ -963,8 +956,8 @@
         // get the simple constraint and build the transitive constraint around it
         constraint = new SingleTransitiveConstraint((Constraint)constraintMap.get(sc));
       } else if (arguments.size() == 2) {
-        Node sc = (Node)arguments.get(TRANSITIVE_ARGUMENT);
-        Node anchor = (Node)arguments.get(ANCHOR_ARGUMENT);
+        Node sc = arguments.get(TRANSITIVE_ARGUMENT);
+        Node anchor = arguments.get(ANCHOR_ARGUMENT);
         if (sc == null || anchor == null) {
           throw new KruleStructureException("Transitive arguments not correct");
         }
@@ -994,24 +987,22 @@
    * @param typeMap Maps constraint nodes to their type.  Used to create a new constraint.
    * @throws KruleStructureException There was an error in the RDF data structure.
    */
-  private List getConstraints(Set constraints, Map constraintLinks, Map typeMap) throws KruleStructureException {
+  private List<ConstraintExpression> getConstraints(Set<Node> constraints, Map<Node,Set<Node>> constraintLinks, Map<Node,URIReference> typeMap) throws KruleStructureException {
     logger.debug("converting nodes to constraint list: " + constraints);
 
     // build the return list
-    List cList = new ArrayList();
+    List<ConstraintExpression> cList = new ArrayList<ConstraintExpression>();
     // go through the arguments
-    Iterator cit = constraints.iterator();
-    while (cit.hasNext()) {
-      Node cNode = (Node)cit.next();
+    for (Node cNode: constraints) {
       logger.debug("converting: " + cNode);
       // get the constraint expression object
       ConstraintExpression constraintExpr = (ConstraintExpression)constraintMap.get(cNode);
       if (constraintExpr == null) {
         logger.debug(cNode.toString() + " not yet mapped to constraint");
         // constraint expression object does not yet exist, get its arguments
-        Set constraintArgNodes = (Set)constraintLinks.get(cNode);
+        Set<Node> constraintArgNodes = constraintLinks.get(cNode);
         // build the constraint expression - get the arguments as a list of constraints
-        List constraintArgs = getConstraints(constraintArgNodes, constraintLinks, typeMap);
+        List<ConstraintExpression> constraintArgs = getConstraints(constraintArgNodes, constraintLinks, typeMap);
         constraintExpr = newJoinConstraint((Node)typeMap.get(cNode), constraintArgs);
       }
       // add the constraint argument to the list
@@ -1028,7 +1019,7 @@
    * @param args The list of arguments for the constraint.
    * @return a new join constraint of the correct type.
    */
-  private ConstraintExpression newJoinConstraint(Node type, List args) throws KruleStructureException {
+  private ConstraintExpression newJoinConstraint(Node type, List<ConstraintExpression> args) throws KruleStructureException {
     logger.debug("Building join constraint of type <" + type + ">: " + args);
 
     if (type.equals(CONSTRAINT_CONJUNCTION)) {
@@ -1041,31 +1032,6 @@
 
 
   /**
-   * Sets a property for a node, creating the entry if it does not exist yet.
-   *
-   * @param map The mapping of nodes to property/values.
-   * @param node The node to set the property for.
-   * @param predicate The property to set.
-   * @param object The value to set the property to.
-   */
-  private static void addProperty(Map map, Node node, URIReference predicate, URIReference object) {
-    // get the current set of properties
-    Map pv = (Map)map.get(node);
-    // check that the map exists
-    if (pv == null) {
-      // no, so create
-      pv = new HashMap();
-      pv.put(predicate, object);
-      // add to the map
-      map.put(node, pv);
-    } else {
-      // update the map to hold the new value
-      pv.put(predicate, object);
-    }
-  }
-
-
-  /**
    * Converts an RDF Node to a constraint element.
    *
    * @param node The node to convert.
@@ -1104,13 +1070,13 @@
    * @param predicate The property to set.
    * @param object The value to set the property to.
    */
-  private static void addProperty(Map map, Node node, URIReference predicate, Node object) {
+  private static void addProperty(Map<Node,Map<Node,Node>> map, Node node, URIReference predicate, Node object) {
     // get the current set of properties
-    Map pv = (Map)map.get(node);
+    Map<Node,Node> pv = map.get(node);
     // check that the map exists
     if (pv == null) {
       // no, so create
-      pv = new HashMap();
+      pv = new HashMap<Node,Node>();
       pv.put(predicate, object);
       // add to the map
       map.put(node, pv);
@@ -1128,13 +1094,13 @@
    * @param node1 The node to map.
    * @param node2 The node to map it to.
    */
-  private static void addLink(Map map, Node node1, Node node2) {
+  private static void addLink(Map<Node,Set<Node>> map, Node node1, Node node2) {
     // get the current set of properties
-    Set links = (Set)map.get(node1);
+    Set<Node> links = map.get(node1);
     // check that the set exists
     if (links == null) {
       // no, so create
-      links = new HashSet();
+      links = new HashSet<Node>();
       links.add(node2);
       // add to the map
       map.put(node1, links);

Modified: branches/mgr-73/src/jar/krule/java/org/mulgara/krule/QueryStruct.java
===================================================================
--- branches/mgr-73/src/jar/krule/java/org/mulgara/krule/QueryStruct.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/krule/java/org/mulgara/krule/QueryStruct.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -35,6 +35,8 @@
 import java.util.Map;
 
 import org.apache.log4j.Logger;
+import org.jrdf.graph.Literal;
+import org.jrdf.graph.Node;
 import org.jrdf.graph.URIReference;
 import org.mulgara.itql.VariableFactoryImpl;
 import org.mulgara.query.ConstantValue;
@@ -44,7 +46,9 @@
 import org.mulgara.query.ModelExpression;
 import org.mulgara.query.ModelResource;
 import org.mulgara.query.ModelUnion;
+import org.mulgara.query.Order;
 import org.mulgara.query.Query;
+import org.mulgara.query.SelectElement;
 import org.mulgara.query.UnconstrainedAnswer;
 import org.mulgara.query.Variable;
 import org.mulgara.query.VariableFactory;
@@ -72,8 +76,8 @@
   /** The selection list. */
   private ConstraintElement[] select = new ConstraintElement[3];
 
-  /** List of elements which are variables. */
-  private List variables;
+  /** List of elements which are variables, or ConstantValues. */
+  private List<SelectElement> variables;
 
   /** The model expresison for the query. */
   private ModelExpression models;
@@ -96,7 +100,12 @@
    * @throws IllegalArgumentException If the types are incorrect, the elements are not named as expected,
    *         or the references are not found in the references map.
    */
-  public QueryStruct(URIReference[] vs, URIReference[] types, Map alias, Map uriReferences, Map varReferences, Map litReferences) {
+  public QueryStruct(
+      URIReference[] vs, URIReference[] types, Map<String,URI> alias,
+      Map<URIReference,URIReference> uriReferences, Map<URIReference,Variable> varReferences,
+      Map<Node,Literal> litReferences
+  ) {
+
     if (vs.length != 3 && types.length != 3) {
       throw new IllegalArgumentException("Wrong number of elements for a rule query");
     }
@@ -104,7 +113,7 @@
     VariableFactory variableFactory = new VariableFactoryImpl();
 
     // set up a list of variables
-    variables = new ArrayList();
+    variables = new ArrayList<SelectElement>();
 
     // convert the parameters to usable objects
     for (int i = 0; i < 3; i++) {
@@ -121,7 +130,7 @@
 
         // get the variable
         select[i] = (Variable)varReferences.get(element);
-        variables.add(select[i]);
+        variables.add((Variable)select[i]);
 
       } else if (types[i].equals(KruleLoader.LITERAL)) {
         
@@ -208,9 +217,10 @@
    *
    * @return a new {@link org.mulgara.query.Query}
    */
+  @SuppressWarnings("unchecked")
   public Query extractQuery() {
     logger.debug("Extracting query");
-    return new Query(variables, models, where, having, Collections.EMPTY_LIST, null, 0, new UnconstrainedAnswer());
+    return new Query(variables, models, where, having, (List<Order>)Collections.EMPTY_LIST, null, 0, new UnconstrainedAnswer());
   }
 
 }

Modified: branches/mgr-73/src/jar/krule/java/org/mulgara/krule/RuleStructure.java
===================================================================
--- branches/mgr-73/src/jar/krule/java/org/mulgara/krule/RuleStructure.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/krule/java/org/mulgara/krule/RuleStructure.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -30,8 +30,6 @@
 // Java 2 standard packages
 import java.net.URI;
 import java.io.Serializable;
-import java.rmi.RemoteException;
-import java.rmi.server.UnicastRemoteObject;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -67,31 +65,31 @@
   private static Logger logger = Logger.getLogger(RuleStructure.class.getName());
 
   /** The rules in the framework. */
-  private Set rules;
+  private Set<Rule> rules;
 
   /** Map of rule names to the rule. */
-  private Map ruleMap;
+  private Map<String,Rule> ruleMap;
 
-  /** The model containing the base data. */
+  /** The model containing the base data.  Current unused. */
   private URI baseModel;
 
   /** The terget model to contain the entailments. */
   private URI targetModel;
 
   /** The current list of rules that have to be run. */
-  private LinkedHashSet runQueue;
+  private LinkedHashSet<Rule> runQueue;
 
   /** The set of axioms pertinent to these rules. */
-  private Set axioms;
+  private Set<org.jrdf.graph.Triple> axioms;
 
 
   /**
    * Principle constructor.
    */
   public RuleStructure() {
-    rules = new HashSet();
-    ruleMap = new HashMap();
-    runQueue = new LinkedHashSet();
+    rules = new HashSet<Rule>();
+    ruleMap = new HashMap<String,Rule>();
+    runQueue = new LinkedHashSet<Rule>();
     axioms = null;
   }
 
@@ -116,8 +114,8 @@
    */
   public void setTrigger(String src, String dest) throws InitializerException {
     // get the rules
-    Rule srcRule = (Rule)ruleMap.get(src);
-    Rule destRule = (Rule)ruleMap.get(dest);
+    Rule srcRule = ruleMap.get(src);
+    Rule destRule = ruleMap.get(dest);
     // check that the rules exist
     if (srcRule == null || destRule == null) {
       throw new InitializerException("Nonexistent rule: " + srcRule == null ? src : dest);
@@ -134,7 +132,7 @@
    * @param axioms A {@link java.util.Set} of {@link org.jrdf.graph.Triple}s
    *   comprising axiomatic statements.
    */
-  public void setAxioms(Set axioms) {
+  public void setAxioms(Set<org.jrdf.graph.Triple> axioms) {
     this.axioms = axioms;
   }
 
@@ -164,7 +162,7 @@
    *
    * @return An iterator for the rules.
    */
-  public Iterator getRuleIterator() {
+  public Iterator<Rule> getRuleIterator() {
     return rules.iterator();
   }
 
@@ -176,11 +174,7 @@
    */
   public String toString() {
     String result = "Rules = {\n";
-    Iterator i = rules.iterator();
-    while (i.hasNext()) {
-      Rule r = (Rule)i.next();
-      result += r.getName() + "\n";
-    }
+    for (Rule r: rules) result += r.getName() + "\n";
     result += "}";
     return result;
   }
@@ -192,26 +186,29 @@
    * @param base The URI of the base data to apply rules to.
    */
   public void setBaseModel(URI base) {
-    Iterator it = rules.iterator();
-    while (it.hasNext()) {
-      Rule rule = (Rule)it.next();
-      rule.setBaseModel(base);
-    }
+    baseModel = base;
+    for (Rule rule: rules) rule.setBaseModel(base);
   }
 
 
   /**
+   * Get the base model for the rules.  Currently unused.
+   *
+   * @param base The URI of the base data to apply rules to.
+   */
+  public URI setBaseModel() {
+    return baseModel;
+  }
+
+
+  /**
    * Set the target model for the rules.
    *
    * @param target The URI of the target model to insert inferences into.
    */
   public void setTargetModel(URI target) {
     targetModel = target;
-    Iterator it = rules.iterator();
-    while (it.hasNext()) {
-      Rule rule = (Rule)it.next();
-      rule.setTargetModel(target);
-    }
+    for (Rule rule: rules) rule.setTargetModel(target);
   }
 
 
@@ -229,7 +226,7 @@
     }
     Session session = (Session)params;
     // set up the run queue
-    runQueue = new LinkedHashSet(rules);
+    runQueue = new LinkedHashSet<Rule>(rules);
     // fill the run queue
     runQueue.addAll(rules);
     Rule currentRule = null;
@@ -294,10 +291,10 @@
    */
   private Rule popRunQueue() {
     // get an iterator for the queue
-    Iterator iterator = runQueue.iterator();
+    Iterator<Rule> iterator = runQueue.iterator();
     // this queue must have data in it
     assert iterator.hasNext();
-    Rule head = (Rule)iterator.next();
+    Rule head = iterator.next();
     iterator.remove();
     return head;
   }

Copied: branches/mgr-73/src/jar/parser (from rev 619, trunk/src/jar/parser)

Deleted: branches/mgr-73/src/jar/parser/build.xml
===================================================================
--- trunk/src/jar/parser/build.xml	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/parser/build.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,127 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!DOCTYPE project>
-
-<!-- =================================================================== -->
-<!--                       Project definition                            -->
-<!-- =================================================================== -->
-<project name="parser" default="parser-jar" basedir="../../..">
-
-  <!-- =================================================================== -->
-  <!--                      Property Definitions                           -->
-  <!-- =================================================================== -->
-
-  <!-- =================================================================== -->
-  <!--                              Imports                                -->
-  <!-- =================================================================== -->
-
-  <!-- =================================================================== -->
-  <!--                          Path Definitions                           -->
-  <!-- =================================================================== -->
-  <path id="parser-classpath">
-    <path refid="common-classpath"/>
-    <fileset file="${query.dist.dir}/${query.jar}"/>
-  </path>
-  <path id="parser-test-classpath">
-    <path refid="parser-classpath"/>
-  </path>
-
-  <target name="parser-clean" description="Removes all compile generated files for the parser">
-    <tstamp/>
-    <delete dir="${parser.obj.dir}"/>
-    <delete dir="${parser.test.dir}"/>
-    <delete dir="${parser.dist.dir}"/>
-  </target>
-
-  <target name="-parser-prepare" description="Creates all directories associated with the parser's compilation"
-      depends="-prepare-build">
-    <mkdir dir="${parser.obj.dir}"/>
-    <mkdir dir="${parser.test.dir}"/>
-    <mkdir dir="${parser.dist.dir}"/>
-    <mkdir dir="${parser.obj.dir}/classes"/>
-    <mkdir dir="${parser.obj.dir}/java"/>
-  </target>
-
-  <target name="parser-compile" depends="-parser-prepare" description="Compiles all parser related files">
-    <javac destdir="${parser.obj.dir}/classes" debug="on" deprecation="on" source="1.5" classpathref="parser-classpath">
-      <src path="${parser.src.dir}/java"/>
-    </javac>
-  </target>
-
-  <target name="parser-jar" depends="parser-compile, -parser-jar-uptodate" unless="parser.jar.uptodate" description="Creates the parser's jar/s">
-    <jar jarfile="${parser.dist.dir}/${parser.jar}">
-      <fileset dir="${parser.obj.dir}/classes" excludes="**/*.java"/>
-    </jar>
-  </target>
-
-  <target name="-parser-jar-uptodate">
-    <uptodate property="parser.jar.uptodate" targetfile="${parser.dist.dir}/${parser.jar}">
-      <srcfiles dir="${parser.obj.dir}/classes" includes="**/*"/>
-    </uptodate>
-  </target>
-
-  <target name="parser-dist"
-          depends="parser-jar"
-          unless="parser.uptodate"
-          description="Performs all tasks related to finalising this parser
-                       and readying it for distribution">
-
-  </target>
-
-  <target name="parser-uptodate">
-
-    <uptodate property="parser.uptodate"
-              targetfile="${dist.dir}/${parser.jar}">
-
-      <srcfiles dir="${parser.dist.dir}" includes="${parser.jar}"/>
-      <srcfiles dir="${query.dist.dir}" includes="${query.jar}"/>
-    </uptodate>
-  </target>
-
-  <target name="parser-test"
-          depends="parser-jar, test-data"
-          description="Carries out unit testing for this parser">
-
-    <antcall target="component-test">
-
-      <param name="classpath.id" value="parser-test-classpath"/>
-      <param name="dir" value="${parser.src.dir}"/>
-      <param name="jar" value="${parser.jar}"/>
-    </antcall>
-
-  </target>
-
-  <target name="parser-javadoc"
-          depends="parser-jar"
-          description="Creates the javadoc for this parser">
-
-    <antcall target="javadoc">
-
-      <param name="javadoc.package" value="org.mulgara.parser.*,
-                                           org.mulgara.store.*"/>
-      <param name="javadoc.classpath" value="parser-classpath"/>
-      <param name="javadoc.sourcepath" value="${parser.src.dir}/java"/>
-    </antcall>
-  </target>
-
-  <target name="parser-help"
-          description="Displays the help information for this parser">
-
-    <!-- This is similar to the main project's help except the information
-         is specific to this parser -->
-
-    <echo message="Welcome to the build script for ${parser.name}."/>
-    <echo message=""/>
-    <echo message="These targets can be invoked as follows:"/>
-    <echo message="  ./build.sh &lt;target&gt;"/>
-    <echo message=""/>
-
-    <java fork="false" classname="org.apache.tools.ant.Main"
-          newenvironment="false">
-
-      <jvmarg value="${arch.bits}"/>
-
-      <arg line="-buildfile ${parser.src.dir}/build.xml -projecthelp"/>
-    </java>
-
-  </target>
-</project>

Copied: branches/mgr-73/src/jar/parser/build.xml (from rev 619, trunk/src/jar/parser/build.xml)
===================================================================
--- branches/mgr-73/src/jar/parser/build.xml	                        (rev 0)
+++ branches/mgr-73/src/jar/parser/build.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,127 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!DOCTYPE project>
+
+<!-- =================================================================== -->
+<!--                       Project definition                            -->
+<!-- =================================================================== -->
+<project name="parser" default="parser-jar" basedir="../../..">
+
+  <!-- =================================================================== -->
+  <!--                      Property Definitions                           -->
+  <!-- =================================================================== -->
+
+  <!-- =================================================================== -->
+  <!--                              Imports                                -->
+  <!-- =================================================================== -->
+
+  <!-- =================================================================== -->
+  <!--                          Path Definitions                           -->
+  <!-- =================================================================== -->
+  <path id="parser-classpath">
+    <path refid="common-classpath"/>
+    <fileset file="${query.dist.dir}/${query.jar}"/>
+  </path>
+  <path id="parser-test-classpath">
+    <path refid="parser-classpath"/>
+  </path>
+
+  <target name="parser-clean" description="Removes all compile generated files for the parser">
+    <tstamp/>
+    <delete dir="${parser.obj.dir}"/>
+    <delete dir="${parser.test.dir}"/>
+    <delete dir="${parser.dist.dir}"/>
+  </target>
+
+  <target name="-parser-prepare" description="Creates all directories associated with the parser's compilation"
+      depends="-prepare-build">
+    <mkdir dir="${parser.obj.dir}"/>
+    <mkdir dir="${parser.test.dir}"/>
+    <mkdir dir="${parser.dist.dir}"/>
+    <mkdir dir="${parser.obj.dir}/classes"/>
+    <mkdir dir="${parser.obj.dir}/java"/>
+  </target>
+
+  <target name="parser-compile" depends="-parser-prepare" description="Compiles all parser related files">
+    <javac destdir="${parser.obj.dir}/classes" debug="on" deprecation="on" source="1.5" classpathref="parser-classpath">
+      <src path="${parser.src.dir}/java"/>
+    </javac>
+  </target>
+
+  <target name="parser-jar" depends="parser-compile, -parser-jar-uptodate" unless="parser.jar.uptodate" description="Creates the parser's jar/s">
+    <jar jarfile="${parser.dist.dir}/${parser.jar}">
+      <fileset dir="${parser.obj.dir}/classes" excludes="**/*.java"/>
+    </jar>
+  </target>
+
+  <target name="-parser-jar-uptodate">
+    <uptodate property="parser.jar.uptodate" targetfile="${parser.dist.dir}/${parser.jar}">
+      <srcfiles dir="${parser.obj.dir}/classes" includes="**/*"/>
+    </uptodate>
+  </target>
+
+  <target name="parser-dist"
+          depends="parser-jar"
+          unless="parser.uptodate"
+          description="Performs all tasks related to finalising this parser
+                       and readying it for distribution">
+
+  </target>
+
+  <target name="parser-uptodate">
+
+    <uptodate property="parser.uptodate"
+              targetfile="${dist.dir}/${parser.jar}">
+
+      <srcfiles dir="${parser.dist.dir}" includes="${parser.jar}"/>
+      <srcfiles dir="${query.dist.dir}" includes="${query.jar}"/>
+    </uptodate>
+  </target>
+
+  <target name="parser-test"
+          depends="parser-jar, test-data"
+          description="Carries out unit testing for this parser">
+
+    <antcall target="component-test">
+
+      <param name="classpath.id" value="parser-test-classpath"/>
+      <param name="dir" value="${parser.src.dir}"/>
+      <param name="jar" value="${parser.jar}"/>
+    </antcall>
+
+  </target>
+
+  <target name="parser-javadoc"
+          depends="parser-jar"
+          description="Creates the javadoc for this parser">
+
+    <antcall target="javadoc">
+
+      <param name="javadoc.package" value="org.mulgara.parser.*,
+                                           org.mulgara.store.*"/>
+      <param name="javadoc.classpath" value="parser-classpath"/>
+      <param name="javadoc.sourcepath" value="${parser.src.dir}/java"/>
+    </antcall>
+  </target>
+
+  <target name="parser-help"
+          description="Displays the help information for this parser">
+
+    <!-- This is similar to the main project's help except the information
+         is specific to this parser -->
+
+    <echo message="Welcome to the build script for ${parser.name}."/>
+    <echo message=""/>
+    <echo message="These targets can be invoked as follows:"/>
+    <echo message="  ./build.sh &lt;target&gt;"/>
+    <echo message=""/>
+
+    <java fork="false" classname="org.apache.tools.ant.Main"
+          newenvironment="false">
+
+      <jvmarg value="${arch.bits}"/>
+
+      <arg line="-buildfile ${parser.src.dir}/build.xml -projecthelp"/>
+    </java>
+
+  </target>
+</project>

Copied: branches/mgr-73/src/jar/parser/java (from rev 619, trunk/src/jar/parser/java)

Deleted: branches/mgr-73/src/jar/parser/parser-build.properties
===================================================================
--- trunk/src/jar/parser/parser-build.properties	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/parser/parser-build.properties	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,15 +0,0 @@
-#
-# Properties used by the Parser module
-#
-
-# Module Name
-parser.name = Parser
-
-# General module properties
-parser.conf.dir      = ${conf.dir}
-parser.src.dir       = ${jar.src.dir}/parser
-parser.obj.dir       = ${jar.obj.dir}/parser
-parser.dist.dir      = ${bin.dir}
-parser.test.dir      = ${test.dir}/parser
-parser.jxtest.dir    = ${jxtest.dir}/parser
-parser.jar           = parser-base-${mulgara-version}.jar

Copied: branches/mgr-73/src/jar/parser/parser-build.properties (from rev 619, trunk/src/jar/parser/parser-build.properties)
===================================================================
--- branches/mgr-73/src/jar/parser/parser-build.properties	                        (rev 0)
+++ branches/mgr-73/src/jar/parser/parser-build.properties	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,15 @@
+#
+# Properties used by the Parser module
+#
+
+# Module Name
+parser.name = Parser
+
+# General module properties
+parser.conf.dir      = ${conf.dir}
+parser.src.dir       = ${jar.src.dir}/parser
+parser.obj.dir       = ${jar.obj.dir}/parser
+parser.dist.dir      = ${bin.dir}
+parser.test.dir      = ${test.dir}/parser
+parser.jxtest.dir    = ${jxtest.dir}/parser
+parser.jar           = parser-base-${mulgara-version}.jar

Modified: branches/mgr-73/src/jar/query/build.xml
===================================================================
--- branches/mgr-73/src/jar/query/build.xml	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/build.xml	2008-01-14 07:33:14 UTC (rev 622)
@@ -22,6 +22,7 @@
     <path refid="common-classpath"/>
     <fileset file="${util.dist.dir}/${util.jar}"/>
     <fileset file="${rules.dist.dir}/${rules.jar}"/>
+    <fileset file="${connection.dist.dir}/${rules.jar}"/>
   </path>
 
   <path id="query-test-classpath">
@@ -30,6 +31,7 @@
 
     <fileset file="${query.dist.dir}/${query.jar}"/>
     <fileset file="${rules.dist.dir}/${rules.jar}"/>
+    <fileset file="${connection.dist.dir}/${rules.jar}"/>
   </path>
 
   <target name="query-clean"
@@ -69,7 +71,7 @@
   </target>
 
   <target name="query-compile"
-          depends="-query-prepare, util-jar, rules-jar, config-jar, -query-unjar-config"
+          depends="-query-prepare, util-jar, rules-jar, connection-jar, config-jar, -query-unjar-config"
           description="Compiles all query related files included generated
                        source code"
           unless="query.classes.uptodate">
@@ -79,6 +81,7 @@
 
       <classpath refid="query-classpath"/>
 
+      <src path="${driver.src.dir}/java"/>
       <src path="${query.src.dir}/java"/>
     </javac>
   </target>

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/connection (from rev 619, trunk/src/jar/query/java/org/mulgara/connection)

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/connection/Connection.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/connection/Connection.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/Connection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,74 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.connection;
-
-import java.net.URI;
-
-import org.mulgara.query.QueryException;
-import org.mulgara.server.Session;
-
-/**
- * A connection for sending commands to a server.
- *
- * @created 2007-09-25
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public interface Connection {
-
-  /**
-   * Give login credentials and security domain to the current session.  This should only be needed
-   * once since the session does not change.
-   * @param securityDomainUri The security domain for the login.
-   * @param user The username.
-   * @param password The password for the given username.
-   */
-  public void setCredentials(URI securityDomainUri, String user, char[] password);
-  
-
-  /**
-   * Give login credentials for the current security domain to the current session.
-   * This should only be needed
-   * once since the session does not change.
-   * @param user The username.
-   * @param password The password for the given username.
-   */
-  public void setCredentials(String user, char[] password);
-
-
-  /**
-   * @return the session
-   */
-  public Session getSession();
-
-
-  /**
-   * Starts and commits transactions on this connection, by turning the autocommit
-   * flag on and off. 
-   * @param autocommit <code>true</code> if the flag is to be on.
-   * @throws QueryException The session could not change state.
-   */
-  public void setAutoCommit(boolean autoCommit) throws QueryException;
-
-
-  /**
-   * @return the autoCommit value
-   */
-  public boolean getAutoCommit();
-
-
-  /**
-   * Closes the current connection.
-   */
-  public void close() throws QueryException;
-}
\ No newline at end of file

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/connection/Connection.java (from rev 619, trunk/src/jar/query/java/org/mulgara/connection/Connection.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/connection/Connection.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/Connection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,74 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.connection;
+
+import java.net.URI;
+
+import org.mulgara.query.QueryException;
+import org.mulgara.server.Session;
+
+/**
+ * A connection for sending commands to a server.
+ *
+ * @created 2007-09-25
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public interface Connection {
+
+  /**
+   * Give login credentials and security domain to the current session.  This should only be needed
+   * once since the session does not change.
+   * @param securityDomainUri The security domain for the login.
+   * @param user The username.
+   * @param password The password for the given username.
+   */
+  public void setCredentials(URI securityDomainUri, String user, char[] password);
+  
+
+  /**
+   * Give login credentials for the current security domain to the current session.
+   * This should only be needed
+   * once since the session does not change.
+   * @param user The username.
+   * @param password The password for the given username.
+   */
+  public void setCredentials(String user, char[] password);
+
+
+  /**
+   * @return the session
+   */
+  public Session getSession();
+
+
+  /**
+   * Starts and commits transactions on this connection, by turning the autocommit
+   * flag on and off. 
+   * @param autocommit <code>true</code> if the flag is to be on.
+   * @throws QueryException The session could not change state.
+   */
+  public void setAutoCommit(boolean autoCommit) throws QueryException;
+
+
+  /**
+   * @return the autoCommit value
+   */
+  public boolean getAutoCommit();
+
+
+  /**
+   * Closes the current connection.
+   */
+  public void close() throws QueryException;
+}
\ No newline at end of file

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionException.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/connection/ConnectionException.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,46 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.connection;
-
-/**
- * An exception indicating a connection problem.
- *
- * @created 2007-08-22
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class ConnectionException extends Exception {
-
-  /** Regenerate this ID if non-private methods are added or removed. */
-  private static final long serialVersionUID = 3768510944925963668L;
-
-
-  /**
-   * Create an exception with a message.
-   * @param message The message to use.
-   */
-  public ConnectionException(String message) {
-    super(message);
-  }
-
-
-  /**
-   * Create an exception caused by another exception, and with a message.
-   * @param message The message to use.
-   * @param cause The original throwable causing this exception.
-   */
-  public ConnectionException(String message, Throwable cause) {
-    super(message, cause);
-  }
-  
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionException.java (from rev 619, trunk/src/jar/query/java/org/mulgara/connection/ConnectionException.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionException.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,46 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.connection;
+
+/**
+ * An exception indicating a connection problem.
+ *
+ * @created 2007-08-22
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class ConnectionException extends Exception {
+
+  /** Regenerate this ID if non-private methods are added or removed. */
+  private static final long serialVersionUID = 3768510944925963668L;
+
+
+  /**
+   * Create an exception with a message.
+   * @param message The message to use.
+   */
+  public ConnectionException(String message) {
+    super(message);
+  }
+
+
+  /**
+   * Create an exception caused by another exception, and with a message.
+   * @param message The message to use.
+   * @param cause The original throwable causing this exception.
+   */
+  public ConnectionException(String message, Throwable cause) {
+    super(message, cause);
+  }
+  
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,204 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.connection;
-
-import java.net.InetAddress;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.UnknownHostException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-import org.mulgara.query.QueryException;
-import org.mulgara.server.Session;
-
-
-/**
- * Creates new connections or reloads from a cache when possible connections.
- * This must NOT be shared between users, as it is designed to cache security credentials!
- *
- * @created 2007-08-21
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class ConnectionFactory {
-
-  /** The logger. */
-  private final static Logger logger = Logger.getLogger(ConnectionFactory.class.getName());
-
-  /** String constant for localhost */
-  private final static String LOCALHOST_NAME = "localhost";
-  
-  /** IP constant for localhost, saved as a string */
-  private final static String LOCALHOST_IP = "127.0.0.1";
-  
-  /** The scheme name for the local protocol */
-  private final static String LOCAL_PROTOCOL = "local";
-  
-  /** The list of known protocols. */
-  private final static String[] PROTOCOLS = { "rmi", "beep", LOCAL_PROTOCOL };
-  
-  /** The list of known local host aliases. */
-  private final static List<String> LOCALHOSTS = new LinkedList<String>();
-  
-  /** Initialize the list of local host aliases. */
-  static {
-    LOCALHOSTS.add(LOCALHOST_NAME);
-    LOCALHOSTS.add(LOCALHOST_IP);
-    try {
-      LOCALHOSTS.add(InetAddress.getLocalHost().getHostAddress());
-      LOCALHOSTS.add(InetAddress.getLocalHost().getHostName());
-    } catch (UnknownHostException e) {
-      logger.error("Unable to get local host address", e);
-    }
-  }
-
-  /** Cache of Connections, based on their server URI. */
-  private Map<URI,SessionConnection> cacheOnUri;
-  /** Cache of Connections, based on their session data. */
-  private Map<Session,SessionConnection> cacheOnSession;
-  
-  /** A local connection.  This is only used if a local session is provided. */
-  private SessionConnection localConnection = null;
-
-  /**
-   * Default constructor.
-   */
-  public ConnectionFactory() {
-    cacheOnUri = new HashMap<URI,SessionConnection>();
-    cacheOnSession = new HashMap<Session,SessionConnection>();
-  }
-
-  /**
-   * Retrieve a connection based on a server URI.
-   * @param serverUri The URI to get the connection to.
-   * @return The new Connection.
-   * @throws ConnectionException There was an error getting a connection.
-   */
-  public Connection newConnection(URI serverUri) throws ConnectionException {
-    SessionConnection c = cacheOnUri.get(serverUri);
-    if (c == null) {
-      if (isLocalServer(serverUri)) {
-        c = (localConnection != null) ? localConnection : new SessionConnection(serverUri, false);
-        addLocalConnection(serverUri, c);
-      } else {
-        c = new SessionConnection(serverUri);
-      }
-      cacheOnUri.put(serverUri, c);
-      cacheOnSession.put(c.getSession(), c);
-    }
-    return c;
-  }
-
-
-  /**
-   * Retrieve a connection for a given session.
-   * @param session The Session the Connection will use..
-   * @return The new Connection.
-   * @throws ConnectionException There was an error getting a connection.
-   */
-  public Connection newConnection(Session session) throws ConnectionException {
-    SessionConnection c = cacheOnSession.get(session);
-    if (c == null) {
-      c = new SessionConnection(session);
-      cacheOnSession.put(session, c);
-      URI serverURI = c.getServerUri();
-      if (serverURI != null) {
-        cacheOnUri.put(serverURI, c);
-        if (session.isLocal()) addLocalConnection(serverURI, c);
-      }
-      if (session.isLocal()) localConnection = c;
-    }
-    return c;
-  }
-
-
-  /**
-   * Close all connections served by this factory. Exceptions are logged, but not acted on.
-   */
-  public void closeAll() {
-    Set<SessionConnection> connectionsToClose = new HashSet<SessionConnection>(cacheOnSession.values());
-    connectionsToClose.addAll(cacheOnUri.values());
-    safeCloseAll(connectionsToClose);
-  }
-
-
-  /**
-   * Closes all connections in a collection. Exceptions are logged, but not acted on.
-   * @param connections The connections to close.
-   */
-  private void safeCloseAll(Iterable<SessionConnection> connections) {
-    for (Connection c: connections) {
-      try {
-        c.close();
-      } catch (QueryException qe) {
-        logger.warn("Unable to close connection", qe);
-      }
-    }
-  }
-  
-
-  /**
-   * Test if a given URI is a local URI.
-   * @param serverUri The URI to test.
-   * @return <code>true</code> if the URI is local.
-   */
-  static boolean isLocalServer(URI serverUri) {
-    if (serverUri == null) return false;
-
-    String scheme = serverUri.getScheme();
-    if (LOCAL_PROTOCOL.equals(scheme)) return true;
-    
-    // check for known protocols
-    boolean found = false;
-    for (String protocol: PROTOCOLS) {
-      if (protocol.equals(serverUri.getScheme())) {
-        found = true;
-        break;
-      }
-    }
-    if (found == false) return false;
-
-    // protocol found.  Now test if the host appears in the localhost list
-    String host = serverUri.getHost();
-    for (String h: LOCALHOSTS) if (h.equalsIgnoreCase(host)) return true;
-
-    // no matching hostnames
-    return false;
-  }
-
-
-  /**
-   * Maps all the possible localhost aliases onto the requested connection.
-   * @param serverUri The basic form of the localhost URI.
-   * @param connection The connection to associate with the local host.
-   */
-  private void addLocalConnection(URI serverUri, SessionConnection connection) {
-    String path = serverUri.getRawPath();
-    for (String protocol: PROTOCOLS) {
-      for (String alias: LOCALHOSTS) {
-        try {
-          URI uri = new URI(protocol, alias, path, null);
-          cacheOnUri.put(uri, connection);
-        } catch (URISyntaxException e) {
-          logger.error("Unable to create a localhost alias URI.");
-        }
-      }
-    }
-  }
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java (from rev 619, trunk/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/ConnectionFactory.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,204 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.connection;
+
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.mulgara.query.QueryException;
+import org.mulgara.server.Session;
+
+
+/**
+ * Creates new connections or reloads from a cache when possible connections.
+ * This must NOT be shared between users, as it is designed to cache security credentials!
+ *
+ * @created 2007-08-21
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class ConnectionFactory {
+
+  /** The logger. */
+  private final static Logger logger = Logger.getLogger(ConnectionFactory.class.getName());
+
+  /** String constant for localhost */
+  private final static String LOCALHOST_NAME = "localhost";
+  
+  /** IP constant for localhost, saved as a string */
+  private final static String LOCALHOST_IP = "127.0.0.1";
+  
+  /** The scheme name for the local protocol */
+  private final static String LOCAL_PROTOCOL = "local";
+  
+  /** The list of known protocols. */
+  private final static String[] PROTOCOLS = { "rmi", "beep", LOCAL_PROTOCOL };
+  
+  /** The list of known local host aliases. */
+  private final static List<String> LOCALHOSTS = new LinkedList<String>();
+  
+  /** Initialize the list of local host aliases. */
+  static {
+    LOCALHOSTS.add(LOCALHOST_NAME);
+    LOCALHOSTS.add(LOCALHOST_IP);
+    try {
+      LOCALHOSTS.add(InetAddress.getLocalHost().getHostAddress());
+      LOCALHOSTS.add(InetAddress.getLocalHost().getHostName());
+    } catch (UnknownHostException e) {
+      logger.error("Unable to get local host address", e);
+    }
+  }
+
+  /** Cache of Connections, based on their server URI. */
+  private Map<URI,SessionConnection> cacheOnUri;
+  /** Cache of Connections, based on their session data. */
+  private Map<Session,SessionConnection> cacheOnSession;
+  
+  /** A local connection.  This is only used if a local session is provided. */
+  private SessionConnection localConnection = null;
+
+  /**
+   * Default constructor.
+   */
+  public ConnectionFactory() {
+    cacheOnUri = new HashMap<URI,SessionConnection>();
+    cacheOnSession = new HashMap<Session,SessionConnection>();
+  }
+
+  /**
+   * Retrieve a connection based on a server URI.
+   * @param serverUri The URI to get the connection to.
+   * @return The new Connection.
+   * @throws ConnectionException There was an error getting a connection.
+   */
+  public Connection newConnection(URI serverUri) throws ConnectionException {
+    SessionConnection c = cacheOnUri.get(serverUri);
+    if (c == null) {
+      if (isLocalServer(serverUri)) {
+        c = (localConnection != null) ? localConnection : new SessionConnection(serverUri, false);
+        addLocalConnection(serverUri, c);
+      } else {
+        c = new SessionConnection(serverUri);
+      }
+      cacheOnUri.put(serverUri, c);
+      cacheOnSession.put(c.getSession(), c);
+    }
+    return c;
+  }
+
+
+  /**
+   * Retrieve a connection for a given session.
+   * @param session The Session the Connection will use..
+   * @return The new Connection.
+   * @throws ConnectionException There was an error getting a connection.
+   */
+  public Connection newConnection(Session session) throws ConnectionException {
+    SessionConnection c = cacheOnSession.get(session);
+    if (c == null) {
+      c = new SessionConnection(session);
+      cacheOnSession.put(session, c);
+      URI serverURI = c.getServerUri();
+      if (serverURI != null) {
+        cacheOnUri.put(serverURI, c);
+        if (session.isLocal()) addLocalConnection(serverURI, c);
+      }
+      if (session.isLocal()) localConnection = c;
+    }
+    return c;
+  }
+
+
+  /**
+   * Close all connections served by this factory. Exceptions are logged, but not acted on.
+   */
+  public void closeAll() {
+    Set<SessionConnection> connectionsToClose = new HashSet<SessionConnection>(cacheOnSession.values());
+    connectionsToClose.addAll(cacheOnUri.values());
+    safeCloseAll(connectionsToClose);
+  }
+
+
+  /**
+   * Closes all connections in a collection. Exceptions are logged, but not acted on.
+   * @param connections The connections to close.
+   */
+  private void safeCloseAll(Iterable<SessionConnection> connections) {
+    for (Connection c: connections) {
+      try {
+        c.close();
+      } catch (QueryException qe) {
+        logger.warn("Unable to close connection", qe);
+      }
+    }
+  }
+  
+
+  /**
+   * Test if a given URI is a local URI.
+   * @param serverUri The URI to test.
+   * @return <code>true</code> if the URI is local.
+   */
+  static boolean isLocalServer(URI serverUri) {
+    if (serverUri == null) return false;
+
+    String scheme = serverUri.getScheme();
+    if (LOCAL_PROTOCOL.equals(scheme)) return true;
+    
+    // check for known protocols
+    boolean found = false;
+    for (String protocol: PROTOCOLS) {
+      if (protocol.equals(serverUri.getScheme())) {
+        found = true;
+        break;
+      }
+    }
+    if (found == false) return false;
+
+    // protocol found.  Now test if the host appears in the localhost list
+    String host = serverUri.getHost();
+    for (String h: LOCALHOSTS) if (h.equalsIgnoreCase(host)) return true;
+
+    // no matching hostnames
+    return false;
+  }
+
+
+  /**
+   * Maps all the possible localhost aliases onto the requested connection.
+   * @param serverUri The basic form of the localhost URI.
+   * @param connection The connection to associate with the local host.
+   */
+  private void addLocalConnection(URI serverUri, SessionConnection connection) {
+    String path = serverUri.getRawPath();
+    for (String protocol: PROTOCOLS) {
+      for (String alias: LOCALHOSTS) {
+        try {
+          URI uri = new URI(protocol, alias, path, null);
+          cacheOnUri.put(uri, connection);
+        } catch (URISyntaxException e) {
+          logger.error("Unable to create a localhost alias URI.");
+        }
+      }
+    }
+  }
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/connection/DummyConnection.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/connection/DummyConnection.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/DummyConnection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,98 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.connection;
-
-import java.net.URI;
-
-import org.apache.log4j.Logger;
-import org.mulgara.query.QueryException;
-import org.mulgara.server.Session;
-
-/**
- * A connection for accepting state changes at the local end with no server involvement
- *
- * @created 2007-09-25
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class DummyConnection implements Connection {
-
-  /** Logger. */
-  private static final Logger logger = Logger.getLogger(DummyConnection.class.getName());
-  
-  /** Indicates the current autocommit state */
-  private boolean autoCommit = true;
-
-  /**
-   * Creates a new connection.
-   */
-  public DummyConnection() {
-  }
-
-
-  /**
-   * Give login credentials and security domain to a session.  This operation is ignored.
-   * @param securityDomainUri The security domain for the login.
-   * @param user The username.
-   * @param password The password for the given username.
-   */
-  public void setCredentials(URI securityDomainUri, String user, char[] password) {
-    logger.warn("Setting credentials on a dummy connection");
-  }
-
-
-  /**
-   * Give login credentials for the current security domain to the current session.
-   * This operation is ignored.
-   * @param user The username.
-   * @param password The password for the given username.
-   */
-  public void setCredentials(String user, char[] password) {
-    logger.warn("Setting credentials on a dummy connection");
-  }
-
-
-  /**
-   * @return always null
-   */
-  public Session getSession() {
-    return null;
-  }
-
-
-  /**
-   * Starts and commits transactions on this connection, by turning the autocommit
-   * flag on and off. 
-   * @param autocommit <code>true</code> if the flag is to be on.
-   * @throws QueryException The session could not change state.
-   */
-  public void setAutoCommit(boolean autoCommit) throws QueryException {
-    this.autoCommit = autoCommit;
-  }
-
-
-  /**
-   * @return the autoCommit value
-   */
-  public boolean getAutoCommit() {
-    return autoCommit;
-  }
-
-
-  /**
-   * Closes the current connection.  Does nothing for this class.
-   */
-  public void close() throws QueryException {
-  }
-  
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/connection/DummyConnection.java (from rev 619, trunk/src/jar/query/java/org/mulgara/connection/DummyConnection.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/connection/DummyConnection.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/DummyConnection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,98 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.connection;
+
+import java.net.URI;
+
+import org.apache.log4j.Logger;
+import org.mulgara.query.QueryException;
+import org.mulgara.server.Session;
+
+/**
+ * A connection for accepting state changes at the local end with no server involvement
+ *
+ * @created 2007-09-25
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class DummyConnection implements Connection {
+
+  /** Logger. */
+  private static final Logger logger = Logger.getLogger(DummyConnection.class.getName());
+  
+  /** Indicates the current autocommit state */
+  private boolean autoCommit = true;
+
+  /**
+   * Creates a new connection.
+   */
+  public DummyConnection() {
+  }
+
+
+  /**
+   * Give login credentials and security domain to a session.  This operation is ignored.
+   * @param securityDomainUri The security domain for the login.
+   * @param user The username.
+   * @param password The password for the given username.
+   */
+  public void setCredentials(URI securityDomainUri, String user, char[] password) {
+    logger.warn("Setting credentials on a dummy connection");
+  }
+
+
+  /**
+   * Give login credentials for the current security domain to the current session.
+   * This operation is ignored.
+   * @param user The username.
+   * @param password The password for the given username.
+   */
+  public void setCredentials(String user, char[] password) {
+    logger.warn("Setting credentials on a dummy connection");
+  }
+
+
+  /**
+   * @return always null
+   */
+  public Session getSession() {
+    return null;
+  }
+
+
+  /**
+   * Starts and commits transactions on this connection, by turning the autocommit
+   * flag on and off. 
+   * @param autocommit <code>true</code> if the flag is to be on.
+   * @throws QueryException The session could not change state.
+   */
+  public void setAutoCommit(boolean autoCommit) throws QueryException {
+    this.autoCommit = autoCommit;
+  }
+
+
+  /**
+   * @return the autoCommit value
+   */
+  public boolean getAutoCommit() {
+    return autoCommit;
+  }
+
+
+  /**
+   * Closes the current connection.  Does nothing for this class.
+   */
+  public void close() throws QueryException {
+  }
+  
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/connection/SessionConnection.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/connection/SessionConnection.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/SessionConnection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,225 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.connection;
-
-import java.net.URI;
-
-import org.apache.log4j.Logger;
-import org.mulgara.query.QueryException;
-import org.mulgara.server.NonRemoteSessionException;
-import org.mulgara.server.Session;
-import org.mulgara.server.SessionFactory;
-import org.mulgara.server.driver.SessionFactoryFinder;
-import org.mulgara.server.driver.SessionFactoryFinderException;
-
-/**
- * A connection for sending commands to a server using a session object.
- *
- * @created 2007-08-21
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class SessionConnection implements Connection {
-
-  /** Logger. */
-  private static final Logger logger = Logger.getLogger(SessionConnection.class.getName());
-  
-  /** The URI for the server to establish a session on. */
-  private URI serverUri;
-  
-  /** The security domain URI. */
-  private URI securityDomainUri;
-  
-  /** The session to use for this connection. */
-  private Session session;
-
-  /** Indicates the current autocommit state */
-  private boolean autoCommit = true;
-
-  /**
-   * Creates a new connection, given a URI to a server.
-   * @param serverUri The URI to connect to.
-   * @throws ConnectionException There was a problem establishing the details needed for a connection.
-   */
-  public SessionConnection(URI serverUri) throws ConnectionException {
-    this(serverUri, true);
-  }
-
-
-  /**
-   * Creates a new connection, given a URI to a server,
-   * and a flag to indicate if the server should be "remote".
-   * @param serverUri The URI to connect to.
-   * @param isRemote <code>true</code> for a remote session, <code>false</code> for local.
-   * @throws ConnectionException There was a problem establishing the details needed for a connection.
-   */
-  SessionConnection(URI serverUri, boolean isRemote) throws ConnectionException {
-    setServerUri(serverUri, isRemote);
-  }
-
-
-  /**
-   * Creates a new connection, given a preassigned session.
-   * @param session The session to connect with.
-   * @throws ConnectionException There was a problem establishing the details needed for a connection.
-   */
-  public SessionConnection(Session session) {
-    this(session, null);
-  }
-  
-  
-  /**
-   * Creates a new connection, given a preassigned session.
-   * @param session The session to connect with.
-   * @throws ConnectionException There was a problem establishing the details needed for a connection.
-   */
-  public SessionConnection(Session session, URI securityDomainUri) {
-    if (session == null) throw new IllegalArgumentException("Cannot create a connection without a server.");
-    setSession(session, securityDomainUri);
-  }
-  
-  
-  /**
-   * Give login credentials and security domain to the current session.  This should only be needed
-   * once since the session does not change.
-   * @param securityDomainUri The security domain for the login.
-   * @param user The username.
-   * @param password The password for the given username.
-   */
-  public void setCredentials(URI securityDomainUri, String user, char[] password) {
-    if (securityDomainUri == null) throw new IllegalArgumentException("Must have a security domain to yuse credentials");
-    this.securityDomainUri = securityDomainUri;
-    setCredentials(user, password);
-  }
-
-
-  /**
-   * Give login credentials for the current security domain to the current session.
-   * This should only be needed
-   * once since the session does not change.
-   * @param user The username.
-   * @param password The password for the given username.
-   */
-  public void setCredentials(String user, char[] password) {
-    if (securityDomainUri == null) throw new IllegalArgumentException("Must have a security domain to yuse credentials");
-    session.login(securityDomainUri, user, password);
-  }
-
-
-  /**
-   * @return the session
-   */
-  public Session getSession() {
-    return session;
-  }
-
-
-  /**
-   * Starts and commits transactions on this connection, by turning the autocommit
-   * flag on and off. 
-   * @param autocommit <code>true</code> if the flag is to be on.
-   * @throws QueryException The session could not change state.
-   */
-  public void setAutoCommit(boolean autoCommit) throws QueryException {
-    if (this.autoCommit != autoCommit) {
-      this.autoCommit = autoCommit;
-      session.setAutoCommit(autoCommit);
-    }
-  }
-
-
-  /**
-   * @return the autoCommit value
-   */
-  public boolean getAutoCommit() {
-    return autoCommit;
-  }
-
-
-  /**
-   * Closes the current connection.
-   */
-  public void close() throws QueryException {
-    if (session != null) {
-      session.close();
-      session = null;
-    }
-  }
-
-  // Private methods //
-
-  /**
-   * @return the serverUri
-   */
-  URI getServerUri() {
-    return serverUri;
-  }
-
-
-  /**
-   * @return the securityDomainUri
-   */
-  URI getSecurityDomainUri() {
-    return securityDomainUri;
-  }
-
-
-  /**
-   * Sets the session information for this connection
-   * @param session The session to set to.
-   * @param securityDomainURI The security domain to use for the session.
-   */
-  private void setSession(Session session, URI securityDomainUri) {
-    this.session = session;
-    this.securityDomainUri = securityDomainUri;
-  }
-
-
-  /**
-   * Establishes a session for this connection.
-   * @param uri The URI to set for the server.
-   * @param isRemote <code>true</code> for a remote session, <code>false</code> for local.
-   * @throws ConnectionException There was a problem establishing a session.
-   */
-  private void setServerUri(URI uri, boolean isRemote) throws ConnectionException {
-    
-    try {
-      if (uri == null) {
-        // no model given, and the factory didn't cache a connection, so make one up.
-        serverUri = SessionFactoryFinder.findServerURI();
-      } else {
-        serverUri = uri;
-      }
-      if (logger.isDebugEnabled()) logger.debug("Set server URI to: " + serverUri);
-
-      if (logger.isDebugEnabled()) logger.debug("Finding session factory for " + uri);
-      
-      SessionFactory sessionFactory = SessionFactoryFinder.newSessionFactory(serverUri, isRemote);
-      if (logger.isDebugEnabled()) logger.debug("Found " + sessionFactory.getClass() +
-          " session factory, obtaining session with " + uri);
-
-      // create a new session and set this connection to it
-      if (securityDomainUri == null) securityDomainUri = sessionFactory.getSecurityDomain();
-      setSession(sessionFactory.newSession(), sessionFactory.getSecurityDomain());
-
-    } catch (SessionFactoryFinderException e) {
-      throw new ConnectionException("Unable to connect to a server", e);
-    } catch (NonRemoteSessionException e) {
-      throw new ConnectionException("Error connecting to the local server", e);
-    } catch (QueryException e) {
-      throw new ConnectionException("Data error in connection attempt", e);
-    }
-    assert session != null;
-  }
-  
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/connection/SessionConnection.java (from rev 619, trunk/src/jar/query/java/org/mulgara/connection/SessionConnection.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/connection/SessionConnection.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/connection/SessionConnection.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,225 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.connection;
+
+import java.net.URI;
+
+import org.apache.log4j.Logger;
+import org.mulgara.query.QueryException;
+import org.mulgara.server.NonRemoteSessionException;
+import org.mulgara.server.Session;
+import org.mulgara.server.SessionFactory;
+import org.mulgara.server.driver.SessionFactoryFinder;
+import org.mulgara.server.driver.SessionFactoryFinderException;
+
+/**
+ * A connection for sending commands to a server using a session object.
+ *
+ * @created 2007-08-21
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class SessionConnection implements Connection {
+
+  /** Logger. */
+  private static final Logger logger = Logger.getLogger(SessionConnection.class.getName());
+  
+  /** The URI for the server to establish a session on. */
+  private URI serverUri;
+  
+  /** The security domain URI. */
+  private URI securityDomainUri;
+  
+  /** The session to use for this connection. */
+  private Session session;
+
+  /** Indicates the current autocommit state */
+  private boolean autoCommit = true;
+
+  /**
+   * Creates a new connection, given a URI to a server.
+   * @param serverUri The URI to connect to.
+   * @throws ConnectionException There was a problem establishing the details needed for a connection.
+   */
+  public SessionConnection(URI serverUri) throws ConnectionException {
+    this(serverUri, true);
+  }
+
+
+  /**
+   * Creates a new connection, given a URI to a server,
+   * and a flag to indicate if the server should be "remote".
+   * @param serverUri The URI to connect to.
+   * @param isRemote <code>true</code> for a remote session, <code>false</code> for local.
+   * @throws ConnectionException There was a problem establishing the details needed for a connection.
+   */
+  SessionConnection(URI serverUri, boolean isRemote) throws ConnectionException {
+    setServerUri(serverUri, isRemote);
+  }
+
+
+  /**
+   * Creates a new connection, given a preassigned session.
+   * @param session The session to connect with.
+   * @throws ConnectionException There was a problem establishing the details needed for a connection.
+   */
+  public SessionConnection(Session session) {
+    this(session, null);
+  }
+  
+  
+  /**
+   * Creates a new connection, given a preassigned session.
+   * @param session The session to connect with.
+   * @throws ConnectionException There was a problem establishing the details needed for a connection.
+   */
+  public SessionConnection(Session session, URI securityDomainUri) {
+    if (session == null) throw new IllegalArgumentException("Cannot create a connection without a server.");
+    setSession(session, securityDomainUri);
+  }
+  
+  
+  /**
+   * Give login credentials and security domain to the current session.  This should only be needed
+   * once since the session does not change.
+   * @param securityDomainUri The security domain for the login.
+   * @param user The username.
+   * @param password The password for the given username.
+   */
+  public void setCredentials(URI securityDomainUri, String user, char[] password) {
+    if (securityDomainUri == null) throw new IllegalArgumentException("Must have a security domain to yuse credentials");
+    this.securityDomainUri = securityDomainUri;
+    setCredentials(user, password);
+  }
+
+
+  /**
+   * Give login credentials for the current security domain to the current session.
+   * This should only be needed
+   * once since the session does not change.
+   * @param user The username.
+   * @param password The password for the given username.
+   */
+  public void setCredentials(String user, char[] password) {
+    if (securityDomainUri == null) throw new IllegalArgumentException("Must have a security domain to yuse credentials");
+    session.login(securityDomainUri, user, password);
+  }
+
+
+  /**
+   * @return the session
+   */
+  public Session getSession() {
+    return session;
+  }
+
+
+  /**
+   * Starts and commits transactions on this connection, by turning the autocommit
+   * flag on and off. 
+   * @param autocommit <code>true</code> if the flag is to be on.
+   * @throws QueryException The session could not change state.
+   */
+  public void setAutoCommit(boolean autoCommit) throws QueryException {
+    if (this.autoCommit != autoCommit) {
+      this.autoCommit = autoCommit;
+      session.setAutoCommit(autoCommit);
+    }
+  }
+
+
+  /**
+   * @return the autoCommit value
+   */
+  public boolean getAutoCommit() {
+    return autoCommit;
+  }
+
+
+  /**
+   * Closes the current connection.
+   */
+  public void close() throws QueryException {
+    if (session != null) {
+      session.close();
+      session = null;
+    }
+  }
+
+  // Private methods //
+
+  /**
+   * @return the serverUri
+   */
+  URI getServerUri() {
+    return serverUri;
+  }
+
+
+  /**
+   * @return the securityDomainUri
+   */
+  URI getSecurityDomainUri() {
+    return securityDomainUri;
+  }
+
+
+  /**
+   * Sets the session information for this connection
+   * @param session The session to set to.
+   * @param securityDomainURI The security domain to use for the session.
+   */
+  private void setSession(Session session, URI securityDomainUri) {
+    this.session = session;
+    this.securityDomainUri = securityDomainUri;
+  }
+
+
+  /**
+   * Establishes a session for this connection.
+   * @param uri The URI to set for the server.
+   * @param isRemote <code>true</code> for a remote session, <code>false</code> for local.
+   * @throws ConnectionException There was a problem establishing a session.
+   */
+  private void setServerUri(URI uri, boolean isRemote) throws ConnectionException {
+    
+    try {
+      if (uri == null) {
+        // no model given, and the factory didn't cache a connection, so make one up.
+        serverUri = SessionFactoryFinder.findServerURI();
+      } else {
+        serverUri = uri;
+      }
+      if (logger.isDebugEnabled()) logger.debug("Set server URI to: " + serverUri);
+
+      if (logger.isDebugEnabled()) logger.debug("Finding session factory for " + uri);
+      
+      SessionFactory sessionFactory = SessionFactoryFinder.newSessionFactory(serverUri, isRemote);
+      if (logger.isDebugEnabled()) logger.debug("Found " + sessionFactory.getClass() +
+          " session factory, obtaining session with " + uri);
+
+      // create a new session and set this connection to it
+      if (securityDomainUri == null) securityDomainUri = sessionFactory.getSecurityDomain();
+      setSession(sessionFactory.newSession(), sessionFactory.getSecurityDomain());
+
+    } catch (SessionFactoryFinderException e) {
+      throw new ConnectionException("Unable to connect to a server", e);
+    } catch (NonRemoteSessionException e) {
+      throw new ConnectionException("Error connecting to the local server", e);
+    } catch (QueryException e) {
+      throw new ConnectionException("Data error in connection attempt", e);
+    }
+    assert session != null;
+  }
+  
+}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/parser (from rev 619, trunk/src/jar/query/java/org/mulgara/parser)

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/parser/Interpreter.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/parser/Interpreter.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/parser/Interpreter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,91 +0,0 @@
-package org.mulgara.parser;
-
-import java.io.IOException;
-import java.util.List;
-
-
-import org.mulgara.query.operation.Command;
-import org.mulgara.query.Query;
-
-
-/**
- * This interface defines the namespaces used while interpreting RDF code.
- * @author pag
- *
- */
-public interface Interpreter {
-
-  //
-  // Constants
-  //
-  /** The rdf namespace prefix. */
-  public static final String RDF = "rdf";
-
-  /** The rdfs namespace prefix. */
-  public static final String RDFS = "rdfs";
-
-  /** The owl namespace prefix. */
-  public static final String OWL = "owl";
-
-  /** The mulgara namespace prefix. */
-  public static final String MULGARA = "mulgara";
-
-  /** The krule namespace prefix. */
-  public static final String KRULE = "krule";
-
-  /** The Dublin Core namespace prefix. */
-  public static final String DC = "dc";
-
-  /** The URI of the rdf namespace. */
-  public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
-
-  /** The URI of the rdfs namespace. */
-  public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#";
-
-  /** The URI of the owl namespace. */
-  public static final String OWL_NS = "http://www.w3.org/2002/07/owl#";
-
-  /** The URI of the mulgara namespace. */
-  public static final String MULGARA_NS = "http://mulgara.org/mulgara#";
-
-  /** The URI of the krule namespace. */
-  public static final String KRULE_NS = "http://mulgara.org/owl/krule/#";
-
-  /** The URI of the dc namespace. */
-  public static final String DC_NS = "http://purl.org/dc/elements/1.1/";
-
-  /**
-  * Parses the given TQL command.
-  *
-  * @param command the command to parse in TQL syntax
-  * @return An AST for the command
-  * @throws MulgaraParserException if the syntax of the command is incorrect
-  * @throws MulgaraLexerException if the syntax of the command is incorrect
-  * @throws IOException if the <var>command</var> cannot be parsed
-  * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
-  */
-  public Command parseCommand(String command) throws MulgaraParserException, MulgaraLexerException, IllegalArgumentException, IOException;
-  
-  /**
-  * Parses the given TQL command.
-  *
-  * @param command the command to parse in TQL syntax
-  * @return A {@link List} of ASTs, one for each command
-  * @throws MulgaraParserException if the syntax of the command is incorrect
-  * @throws MulgaraLexerException if the syntax of the command is incorrect
-  * @throws IOException if the <var>command</var> cannot be parsed
-  * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
-  */
-  public List<Command> parseCommands(String command) throws MulgaraParserException, MulgaraLexerException, IOException, IllegalArgumentException;
-  
-  /**
-  * Parse a string into a {@link Query}. Convenience method over parseCommand.
-  *
-  * @param queryString a string containing an ITQL query
-  * @return the corresponding {@link Query} instance
-  * @throws IOException if <var>queryString</var> can't be buffered.
-  * @throws MulgaraLexerException if <var>queryString</var> can't be tokenized.
-  * @throws MulgaraParserException if <var>queryString</var> is not syntactic.
-  */
-  public Query parseQuery(String queryString) throws IOException, MulgaraLexerException, MulgaraParserException;
-}
\ No newline at end of file

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/parser/Interpreter.java (from rev 619, trunk/src/jar/query/java/org/mulgara/parser/Interpreter.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/parser/Interpreter.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/parser/Interpreter.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,91 @@
+package org.mulgara.parser;
+
+import java.io.IOException;
+import java.util.List;
+
+
+import org.mulgara.query.operation.Command;
+import org.mulgara.query.Query;
+
+
+/**
+ * This interface defines the namespaces used while interpreting RDF code.
+ * @author pag
+ *
+ */
+public interface Interpreter {
+
+  //
+  // Constants
+  //
+  /** The rdf namespace prefix. */
+  public static final String RDF = "rdf";
+
+  /** The rdfs namespace prefix. */
+  public static final String RDFS = "rdfs";
+
+  /** The owl namespace prefix. */
+  public static final String OWL = "owl";
+
+  /** The mulgara namespace prefix. */
+  public static final String MULGARA = "mulgara";
+
+  /** The krule namespace prefix. */
+  public static final String KRULE = "krule";
+
+  /** The Dublin Core namespace prefix. */
+  public static final String DC = "dc";
+
+  /** The URI of the rdf namespace. */
+  public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+
+  /** The URI of the rdfs namespace. */
+  public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#";
+
+  /** The URI of the owl namespace. */
+  public static final String OWL_NS = "http://www.w3.org/2002/07/owl#";
+
+  /** The URI of the mulgara namespace. */
+  public static final String MULGARA_NS = "http://mulgara.org/mulgara#";
+
+  /** The URI of the krule namespace. */
+  public static final String KRULE_NS = "http://mulgara.org/owl/krule/#";
+
+  /** The URI of the dc namespace. */
+  public static final String DC_NS = "http://purl.org/dc/elements/1.1/";
+
+  /**
+  * Parses the given TQL command.
+  *
+  * @param command the command to parse in TQL syntax
+  * @return An AST for the command
+  * @throws MulgaraParserException if the syntax of the command is incorrect
+  * @throws MulgaraLexerException if the syntax of the command is incorrect
+  * @throws IOException if the <var>command</var> cannot be parsed
+  * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
+  */
+  public Command parseCommand(String command) throws MulgaraParserException, MulgaraLexerException, IllegalArgumentException, IOException;
+  
+  /**
+  * Parses the given TQL command.
+  *
+  * @param command the command to parse in TQL syntax
+  * @return A {@link List} of ASTs, one for each command
+  * @throws MulgaraParserException if the syntax of the command is incorrect
+  * @throws MulgaraLexerException if the syntax of the command is incorrect
+  * @throws IOException if the <var>command</var> cannot be parsed
+  * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
+  */
+  public List<Command> parseCommands(String command) throws MulgaraParserException, MulgaraLexerException, IOException, IllegalArgumentException;
+  
+  /**
+  * Parse a string into a {@link Query}. Convenience method over parseCommand.
+  *
+  * @param queryString a string containing an ITQL query
+  * @return the corresponding {@link Query} instance
+  * @throws IOException if <var>queryString</var> can't be buffered.
+  * @throws MulgaraLexerException if <var>queryString</var> can't be tokenized.
+  * @throws MulgaraParserException if <var>queryString</var> is not syntactic.
+  */
+  public Query parseQuery(String queryString) throws IOException, MulgaraLexerException, MulgaraParserException;
+}
\ No newline at end of file

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,19 +0,0 @@
-package org.mulgara.parser;
-
-public class MulgaraLexerException extends Exception {
-
-  private static final long serialVersionUID = -5853073510057952109L;
-
-  public MulgaraLexerException(String message) {
-    super(message);
-  }
-
-  public MulgaraLexerException(Throwable cause) {
-    super(cause.getMessage(), cause);
-  }
-
-  public MulgaraLexerException(String message, Throwable cause) {
-    super(message, cause);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java (from rev 619, trunk/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraLexerException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,19 @@
+package org.mulgara.parser;
+
+public class MulgaraLexerException extends Exception {
+
+  private static final long serialVersionUID = -5853073510057952109L;
+
+  public MulgaraLexerException(String message) {
+    super(message);
+  }
+
+  public MulgaraLexerException(Throwable cause) {
+    super(cause.getMessage(), cause);
+  }
+
+  public MulgaraLexerException(String message, Throwable cause) {
+    super(message, cause);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,19 +0,0 @@
-package org.mulgara.parser;
-
-public class MulgaraParserException extends Exception {
-
-  private static final long serialVersionUID = -7724312286750583118L;
-
-  public MulgaraParserException(String message) {
-    super(message);
-  }
-
-  public MulgaraParserException(Throwable cause) {
-    super(cause.getMessage(), cause);
-  }
-
-  public MulgaraParserException(String message, Throwable cause) {
-    super(message, cause);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java (from rev 619, trunk/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/parser/MulgaraParserException.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,19 @@
+package org.mulgara.parser;
+
+public class MulgaraParserException extends Exception {
+
+  private static final long serialVersionUID = -7724312286750583118L;
+
+  public MulgaraParserException(String message) {
+    super(message);
+  }
+
+  public MulgaraParserException(Throwable cause) {
+    super(cause.getMessage(), cause);
+  }
+
+  public MulgaraParserException(String message, Throwable cause) {
+    super(message, cause);
+  }
+
+}

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/AbstractConstraintExpression.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/AbstractConstraintExpression.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/AbstractConstraintExpression.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -62,24 +62,19 @@
   /**
    * A set of all variables the compose the constraint.
    */
-  protected Set variables = null;
+  protected Set<Variable> variables = null;
 
   /**
    * The operands.
    */
-  protected ArrayList elements;
+  protected ArrayList<ConstraintExpression> elements;
 
   public boolean equals(Object o) {
-    if (o == null) {
-      return false;
-    }
-    if (o == this) {
-      return true;
-    }
+    if (o == null) return false;
+    if (o == this) return true;
 
     if (o instanceof ConstraintExpression) {
-      ConstraintExpression ce = (ConstraintExpression) o;
-      return (getVariables().equals(((ConstraintExpression) o).getVariables()));
+      return (getVariables().equals(((ConstraintExpression)o).getVariables()));
     } else {
       return false;
     }

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/AggregateFunction.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/AggregateFunction.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/AggregateFunction.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -49,7 +49,7 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
-public abstract class AggregateFunction implements Serializable {
+public abstract class AggregateFunction implements SelectElement, Serializable {
 
   /**
    * Allow newer compiled version of the stub to operate when changes

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstantValue.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstantValue.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstantValue.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -48,7 +48,7 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
-public class ConstantValue implements Serializable {
+public class ConstantValue implements SelectElement, Serializable {
 
   /**
    * Allow newer compiled version of the stub to operate when changes

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/Constraint.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/Constraint.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/Constraint.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -29,7 +29,6 @@
 
 package org.mulgara.query;
 
-import java.util.Set;
 
 /**
  * A variable and its ordering, for composing <code>ORDER BY</code> clauses.

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintConjunction.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintConjunction.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintConjunction.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -51,7 +51,7 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
-public class ConstraintConjunction extends ConstraintOperation {
+public class ConstraintConjunction extends ConstraintFilteredOperation {
 
   /**
    * Allow newer compiled version of the stub to operate when changes
@@ -71,27 +71,24 @@
    * @param lhs a non-<code>null</code> constraint expression
    * @param rhs another non-<code>null</code> constraint expression
    */
-  public ConstraintConjunction(ConstraintExpression lhs,
-      ConstraintExpression rhs) {
+  public ConstraintConjunction(ConstraintExpression lhs, ConstraintExpression rhs) {
     super(lhs, rhs);
   }
 
   /**
-   * CONSTRUCTOR ConstraintConjunction TO DO
-   *
-   * @param elements PARAMETER TO DO
+   * Build a conjunction with a {@link List} of several children constraint expressions
+   * @param elements a {@link List} of constraint expressions.
    */
-  public ConstraintConjunction(List elements) {
+  public ConstraintConjunction(List<ConstraintExpression> elements) {
     super(elements);
   }
 
   /**
-   * CONSTRUCTOR ConstraintConjunction TO DO
-   *
-   * @param elements PARAMETER TO DO
+   * Build a conjunction with a {@link Collection} of several children constraint expressions
+   * @param elements a {@link Collection} of {@link ConstraintExpression}s.
    */
-  public ConstraintConjunction(Collection elements) {
-    super(new ArrayList(elements));
+  public ConstraintConjunction(Collection<ConstraintExpression> elements) {
+    super(new ArrayList<ConstraintExpression>(elements));
   }
 
 
@@ -102,7 +99,7 @@
    */
   public ConstraintConjunction getFiltered() {
 
-    List elements = new ArrayList(this.getElements());
+    List<ConstraintExpression> elements = new ArrayList<ConstraintExpression>(this.getElements());
     filter(elements);
 
     return new ConstraintConjunction(elements);
@@ -115,45 +112,6 @@
    * @return The Name value
    */
   String getName() {
-
     return " and ";
   }
-
-
-  /**
-   * METHOD TO DO
-   *
-   * @param product PARAMETER TO DO
-   */
-  private void filter(List product) {
-
-    Set o1 = new HashSet();
-
-    // Variables which occur at least once.
-    Set o2 = new HashSet();
-
-    // Variables which occur two or more times.
-    // Get a set of variables which occur two or more times.
-    for (Iterator pIt = product.iterator(); pIt.hasNext(); ) {
-
-      ConstraintExpression oc = (ConstraintExpression) pIt.next();
-      Set ocVars = oc.getVariables();
-      Set vars = new HashSet(ocVars);
-      vars.retainAll(o1);
-      o2.addAll(vars);
-      o1.addAll(ocVars);
-    }
-
-    for (Iterator pIt = product.iterator(); pIt.hasNext(); ) {
-
-      ConstraintExpression oc = (ConstraintExpression) pIt.next();
-      Set vars = new HashSet(oc.getVariables());
-      vars.retainAll(o2);
-
-      if (vars.isEmpty()) {
-
-        pIt.remove();
-      }
-    }
-  }
 }

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDifference.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDifference.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDifference.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -48,7 +48,7 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
-public class ConstraintDifference extends ConstraintOperation {
+public class ConstraintDifference extends ConstraintFilteredOperation {
 
   /**
    * Allow newer compiled version of the stub to operate when changes
@@ -80,11 +80,11 @@
    */
   public ConstraintDifference getFiltered() {
 
-    List elements = new ArrayList(this.getElements());
+    List<ConstraintExpression> elements = new ArrayList<ConstraintExpression>(this.getElements());
     filter(elements);
 
     assert elements.size() == 2;
-    return new ConstraintDifference((ConstraintExpression)elements.get(0), (ConstraintExpression)elements.get(1));
+    return new ConstraintDifference(elements.get(0), elements.get(1));
   }
 
 
@@ -94,45 +94,7 @@
    * @return The Name value
    */
   String getName() {
-
     return " minus ";
   }
 
-
-  /**
-   * METHOD TO DO
-   *
-   * @param product PARAMETER TO DO
-   */
-  private void filter(List product) {
-
-    Set o1 = new HashSet();
-
-    // Variables which occur at least once.
-    Set o2 = new HashSet();
-
-    // Variables which occur two or more times.
-    // Get a set of variables which occur two or more times.
-    for (Iterator pIt = product.iterator(); pIt.hasNext(); ) {
-
-      ConstraintExpression oc = (ConstraintExpression) pIt.next();
-      Set ocVars = oc.getVariables();
-      Set vars = new HashSet(ocVars);
-      vars.retainAll(o1);
-      o2.addAll(vars);
-      o1.addAll(ocVars);
-    }
-
-    for (Iterator pIt = product.iterator(); pIt.hasNext(); ) {
-
-      ConstraintExpression oc = (ConstraintExpression) pIt.next();
-      Set vars = new HashSet(oc.getVariables());
-      vars.retainAll(o2);
-
-      if (vars.isEmpty()) {
-
-        pIt.remove();
-      }
-    }
-  }
 }

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDisjunction.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDisjunction.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintDisjunction.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -63,27 +63,21 @@
   static final long serialVersionUID = -6389569358524360795L;
 
   /**
-   * A set of all variables the compose the constraint.
-   */
-  private Set variables = null;
-
-  /**
    * Construct a constraint disjunction.
    *
    * @param lhs a non-<code>null</code> constraint expression
    * @param rhs another non-<code>null</code> constraint expression
    */
-  public ConstraintDisjunction(ConstraintExpression lhs,
-      ConstraintExpression rhs) {
+  public ConstraintDisjunction(ConstraintExpression lhs, ConstraintExpression rhs) {
     super(lhs, rhs);
   }
 
   /**
-   * CONSTRUCTOR ConstraintDisjunction TO DO
+   * Create a Disjunction (OR expression) between several constraint expressions.
    *
-   * @param elements PARAMETER TO DO
+   * @param elements The expressions to perform a disjunction on.
    */
-  public ConstraintDisjunction(List elements) {
+  public ConstraintDisjunction(List<ConstraintExpression> elements) {
     super(elements);
   }
 

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintExpression.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintExpression.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintExpression.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -61,10 +61,9 @@
   static final long serialVersionUID = 3476137906321174349L;
 
   /**
-   * Get all constraints which are variables. For back-compatibility, this
-   * method currently ignores the fourth element of the triple.
+   * Get all variables from component constraints.
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables();
+  public Set<Variable> getVariables();
 }

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFalse.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFalse.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFalse.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -101,8 +101,8 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
-    return new HashSet();
+  public Set<Variable> getVariables() {
+    return new HashSet<Variable>();
   }
 
   //

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFilteredOperation.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/ConstraintFilteredOperation.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFilteredOperation.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintFilteredOperation.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,81 @@
+/**
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * A constraint operation where the result uses an intersection of variables from the parameters.
+ *
+ * @created Aug 20, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public abstract class ConstraintFilteredOperation extends ConstraintOperation {
+
+  /**
+   * Create a binary operation for requiring intersecting variables.
+   * @param lhs The first constraint operations.
+   * @param rhs The second constraint operations.
+   */
+  public ConstraintFilteredOperation(ConstraintExpression lhs, ConstraintExpression rhs) {
+    super(lhs, rhs);
+  }
+
+
+  /**
+   * Create an operation for requiring intersecting variables.
+   * @param elements The list of expressions to use as parameters.
+   */
+  public ConstraintFilteredOperation(List<ConstraintExpression> elements) {
+    super(elements);
+  }
+
+  /**
+   * Remove the constraint expressions from the product that have non-intersecting variables.
+   *
+   * @param product The list of constraints to test and modify.
+   */
+  protected void filter(List<ConstraintExpression> product) {
+  
+    Set<Variable> o1 = new HashSet<Variable>();
+  
+    // Variables which occur at least once.
+    Set<Variable> o2 = new HashSet<Variable>();
+  
+    // Variables which occur two or more times.
+    // Get a set of variables which occur two or more times.
+    for (ConstraintExpression oc: product) {
+  
+      Set<Variable> ocVars = oc.getVariables();
+      Set<Variable> vars = new HashSet<Variable>(ocVars);
+      vars.retainAll(o1);
+      o2.addAll(vars);
+      o1.addAll(ocVars);
+    }
+  
+    // remove the expressions which have non-intersecting variables
+    for (Iterator<ConstraintExpression> pIt = product.iterator(); pIt.hasNext(); ) {
+  
+      ConstraintExpression oc = pIt.next();
+      Set<Variable> vars = new HashSet<Variable>(oc.getVariables());
+      vars.retainAll(o2);
+  
+      if (vars.isEmpty()) pIt.remove();
+    }
+  }
+
+}
\ No newline at end of file

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintHaving.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintHaving.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintHaving.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -33,11 +33,9 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 import org.jrdf.graph.*;
 
-// Local packages
-import org.mulgara.query.rdf.URIReferenceImpl;
 
 /**
  * An equality constraint. The elements within the constraint can be either variables or
@@ -62,11 +60,8 @@
  */
 public abstract class ConstraintHaving extends AbstractConstraintExpression implements Constraint {
 
-  /**
-   * Logger.
-   */
-  private final static Category logger =
-      Category.getInstance(ConstraintHaving.class.getName());
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(ConstraintHaving.class.getName());
 
   /**
     * The 4-tuple of elements (either nodes or variables)
@@ -151,15 +146,13 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
+  public Set<Variable> getVariables() {
     if (variables == null) {
-      Set v = new HashSet();
+      Set<Variable> v = new HashSet<Variable>();
       Variable e = getVariable();
-      if (!e.getName().startsWith("_")) {
-        v.add(e);
-      }
+      if (!e.getName().startsWith("_")) v.add(e);
       if (element[3] instanceof Variable && !((Variable)element[3]).getName().startsWith("_")) {
-        v.add(element[3]);
+        v.add((Variable)element[3]);
       }
       variables = Collections.unmodifiableSet(v);
     }
@@ -174,18 +167,12 @@
    * @return <code>true</code> if object is the same as this.
    */
   public boolean equals(Object object) {
-    if (object == null) {
-      return false;
-    }
+    if (object == null) return false;
 
-    if (object == this) {
-      return true;
-    }
+    if (object == this) return true;
 
     // Check that the given object is the correct class
-    if (!object.getClass().equals(this.getClass())) {
-      return false;
-    }
+    if (!object.getClass().equals(this.getClass())) return false;
 
     // Check each element.
     ConstraintHaving tmpConstraint = (ConstraintHaving) object;

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintImpl.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintImpl.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintImpl.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -33,7 +33,7 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 /**
  * A constraint. The elements within the constraint can be either variables or
@@ -56,8 +56,7 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
-public class ConstraintImpl extends AbstractConstraintExpression implements
-    Constraint {
+public class ConstraintImpl extends AbstractConstraintExpression implements Constraint {
 
  /**
   * Allow newer compiled version of the stub to operate when changes
@@ -67,11 +66,8 @@
   */
   static final long serialVersionUID = -3127160729187334757L;
 
-  /**
-   * Logger.
-   */
-  private final static Category logger =
-      Category.getInstance(ConstraintImpl.class.getName());
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(ConstraintImpl.class.getName());
 
   /**
    * The 4-tuple of elements (either nodes or variables)
@@ -172,18 +168,17 @@
   }
 
   /**
-   * Get all constraints which are variables. For back-compatibility, this
-   * method currently ignores the fourth element of the triple.
+   * Get all constraints which are variables. This
+   * method uses the fourth element of the triple.
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
+  public Set<Variable> getVariables() {
     if (variables == null) {
-      Set v = new HashSet();
+      Set<Variable> v = new HashSet<Variable>();
       for (int i = 0; i < 4; i++) {
-        if (element[i] instanceof Variable &&
-            ! ( (Variable) element[i]).getName().startsWith("_")) {
-          v.add(element[i]);
+        if (element[i] instanceof Variable && !((Variable)element[i]).getName().startsWith("_")) {
+          v.add((Variable)element[i]);
         }
       }
       variables = Collections.unmodifiableSet(v);
@@ -194,25 +189,17 @@
   /**
    * Equality is by value.
    *
-   * @param object PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
+   * @param object The instance to compare to
+   * @return <code>true</code> iff objects are compatible and contain the same data.
    */
   public boolean equals(Object object) {
     // FIXME: Refactor to exploit equals() method on ConstraintExpression.
-    if (object == null) {
+    if (object == null) return false;
+    if (object == this) return true;
 
-      return false;
-    }
-
-    if (object == this) {
-
-      return true;
-    }
-
     boolean returnValue = false;
 
-    // Check that the given object is the correct class if so check each
-    // element.
+    // Check that the given object is the correct class if so check each element.
     if (object.getClass().equals(this.getClass())) {
 
       Constraint tmpConstraint = (Constraint) object;
@@ -227,10 +214,10 @@
     return returnValue;
   }
 
+
   /**
-   * METHOD TO DO
-   *
-   * @return RETURNED VALUE TO DO
+   * Generate a relatively unique number for the given data
+   * @return A reproducible number that changes with the data
    */
   public int hashCode() {
 
@@ -238,6 +225,7 @@
         element[2].hashCode() + element[3].hashCode();
   }
 
+
   /**
    * Creates a string representation of these constraints. A typical result
    * might be <code>[$x &lt;urn:foo&gt; 'bar' $0]</code>.

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintIs.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintIs.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintIs.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -33,7 +33,7 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 // Local packages
 import org.mulgara.query.rdf.URIReferenceImpl;
@@ -61,12 +61,12 @@
  */
 public class ConstraintIs extends AbstractConstraintExpression implements Constraint {
 
-  /**
-   * Logger.
-   */
-  private final static Category logger =
-      Category.getInstance(ConstraintIs.class.getName());
+  /** Serialization ID for marshalling */
+  private static final long serialVersionUID = 7952821738407976852L;
 
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(ConstraintIs.class.getName());
+
   /** Create the predicate to be used to indicate equality. */
   public static final URIReferenceImpl MULGARA_IS = new URIReferenceImpl(SpecialPredicates.MULGARA_IS);
 
@@ -168,20 +168,19 @@
 
 
   /**
-   * Get all constraints which are variables. For back-compatibility, this
-   * method currently ignores the fourth element of the triple.
+   * Get all constraints which are variables. This
+   * method now uses the fourth element of the triple.
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
+  public Set<Variable> getVariables() {
     if (variables == null) {
-      Set v = new HashSet();
+      Set<Variable> v = new HashSet<Variable>();
       Variable e = getVariable();
-      if (!e.getName().startsWith("_")) {
-        v.add(e);
-      }
+      if (!e.getName().startsWith("_")) v.add(e);
+      // now check the graph
       if (element[3] instanceof Variable && !((Variable)element[3]).getName().startsWith("_")) {
-        v.add(element[3]);
+        v.add((Variable)element[3]);
       }
       variables = Collections.unmodifiableSet(v);
     }
@@ -196,18 +195,12 @@
    * @return <code>true</code> if object is the same as this.
    */
   public boolean equals(Object object) {
-    if (object == null) {
-      return false;
-    }
+    if (object == null) return false;
 
-    if (object == this) {
-      return true;
-    }
+    if (object == this) return true;
 
     // Check that the given object is the correct class
-    if (!object.getClass().equals(this.getClass())) {
-      return false;
-    }
+    if (!object.getClass().equals(this.getClass())) return false;
 
     // Check each element.
     ConstraintIs tmpConstraint = (ConstraintIs) object;

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNegation.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNegation.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNegation.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -32,7 +32,7 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Logger;
+// import org.apache.log4j.Logger;
 
 /**
  * A constraint expression composed of the negation (logical NOT) of one
@@ -57,11 +57,8 @@
  */
 public class ConstraintNegation implements Constraint {
 
-  /**
-   * The logger
-   */
-  private final static Logger logger =
-      Logger.getLogger(ConstraintNegation.class.getName());
+  // /** The logger */
+  // private final static Logger logger = Logger.getLogger(ConstraintNegation.class.getName());
 
   /**
    * Allow newer compiled version of the stub to operate when changes
@@ -125,7 +122,7 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
+  public Set<Variable> getVariables() {
     return constraint.getVariables();
   }
 

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNotOccurs.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNotOccurs.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintNotOccurs.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -27,11 +27,8 @@
 
 package org.mulgara.query;
 
-// Java 2 standard packages
-import java.util.*;
-
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 // Local packages
 import org.mulgara.query.rdf.URIReferenceImpl;
@@ -59,11 +56,16 @@
  */
 public class ConstraintNotOccurs extends ConstraintHaving {
 
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(ConstraintOccurs.class.getName());
+
   /**
-   * Logger.
+   * Allow newer compiled version of the stub to operate when changes
+   * have not occurred with the class.
+   * NOTE : update this serialVersionUID when a method or a public member is
+   * deleted.
    */
-  private final static Category logger =
-      Category.getInstance(ConstraintOccurs.class.getName());
+  private static final long serialVersionUID = 1125962088193740608L;
 
   /**
    * Create the predicate to be used to indicate equality.

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccurs.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccurs.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccurs.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -27,11 +27,8 @@
 
 package org.mulgara.query;
 
-// Java 2 standard packages
-import java.util.*;
-
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 // Local packages
 import org.mulgara.query.rdf.URIReferenceImpl;
@@ -59,11 +56,16 @@
  */
 public class ConstraintOccurs extends ConstraintHaving {
 
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(ConstraintOccurs.class.getName());
+
   /**
-   * Logger.
+   * Allow newer compiled version of the stub to operate when changes
+   * have not occurred with the class.
+   * NOTE : update this serialVersionUID when a method or a public member is
+   * deleted.
    */
-  private final static Category logger =
-      Category.getInstance(ConstraintOccurs.class.getName());
+  private static final long serialVersionUID = -5881219717825517770L;
 
   /**
    * Create the predicate to be used to indicate equality.

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursLessThan.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursLessThan.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursLessThan.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -27,11 +27,8 @@
 
 package org.mulgara.query;
 
-// Java 2 standard packages
-import java.util.*;
-
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 // Local packages
 import org.mulgara.query.rdf.URIReferenceImpl;
@@ -59,11 +56,16 @@
  */
 public class ConstraintOccursLessThan extends ConstraintHaving {
 
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(ConstraintOccursLessThan.class.getName());
+
   /**
-   * Logger.
+   * Allow newer compiled version of the stub to operate when changes
+   * have not occurred with the class.
+   * NOTE : update this serialVersionUID when a method or a public member is
+   * deleted.
    */
-  private final static Category logger =
-      Category.getInstance(ConstraintOccursLessThan.class.getName());
+  private static final long serialVersionUID = -4589400796204186895L;
 
   /**
    * Create the predicate to be used to indicate equality.

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursMoreThan.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursMoreThan.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOccursMoreThan.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -27,11 +27,8 @@
 
 package org.mulgara.query;
 
-// Java 2 standard packages
-import java.util.*;
-
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 // Local packages
 import org.mulgara.query.rdf.URIReferenceImpl;
@@ -42,7 +39,7 @@
  *
  * @created 2004-08-12
  *
- * @author <a href="mailto:pag at tucanatech.com">Paul Gearon</a>
+ * @author <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
  *
  * @version $Revision: 1.9 $
  *
@@ -59,11 +56,16 @@
  */
 public class ConstraintOccursMoreThan extends ConstraintHaving {
 
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(ConstraintOccursMoreThan.class.getName());
+
   /**
-   * Logger.
+   * Allow newer compiled version of the stub to operate when changes
+   * have not occurred with the class.
+   * NOTE : update this serialVersionUID when a method or a public member is
+   * deleted.
    */
-  private final static Category logger =
-      Category.getInstance(ConstraintOccursMoreThan.class.getName());
+  private static final long serialVersionUID = 8077840346515987908L;
 
   /**
    * Create the predicate to be used to indicate equality.

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOperation.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOperation.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintOperation.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -31,7 +31,7 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 /**
  * A constraint expression composed of two subexpressions and a dyadic operator.
@@ -64,11 +64,8 @@
    */
   static final long serialVersionUID = -236847137057853871L;
 
-  /**
-   * Logger.
-   */
-  private static Category logger =
-      Category.getInstance(ConstraintOperation.class.getName());
+  // /** Logger. */
+  // private static Category logger = Category.getInstance(ConstraintOperation.class.getName());
 
   //
   // Constructor
@@ -84,21 +81,17 @@
    */
   protected ConstraintOperation(ConstraintExpression lhs, ConstraintExpression rhs) {
     // Validate "lhs" parameter
-    if (lhs == null) {
-      throw new IllegalArgumentException("Null \"lhs\" parameter");
-    }
+    if (lhs == null) throw new IllegalArgumentException("Null \"lhs\" parameter");
 
     // Validate "rhs" parameter
-    if (rhs == null) {
-      throw new IllegalArgumentException("Null \"rhs\" parameter");
-    }
+    if (rhs == null) throw new IllegalArgumentException("Null \"rhs\" parameter");
 
     // Initialize fields
-    elements = new ArrayList(2);
+    elements = new ArrayList<ConstraintExpression>(2);
 
     // Add the LHS
     if (lhs.getClass().equals(getClass())) {
-      elements.addAll( ( (ConstraintOperation) lhs).getElements());
+      elements.addAll(((ConstraintOperation)lhs).getElements());
     } else {
       elements.add(lhs);
     }
@@ -112,33 +105,17 @@
   }
 
   /**
-   * CONSTRUCTOR ConstraintOperation TO DO
+   * Creates a new ConstraintOperation build on a list of ConstraintExpression
    *
-   * @param elements PARAMETER TO DO
+   * @param elements A list of ConstraintExpression to be the parameters of this expression
    */
-  protected ConstraintOperation(List elements) {
+  protected ConstraintOperation(List<ConstraintExpression> elements) {
     // Validate "elements" parameter
-    if (elements == null) {
-      throw new IllegalArgumentException("Null \"elements\" parameter");
-    }
+    if (elements == null) throw new IllegalArgumentException("Null \"elements\" parameter");
+    // assert elements.size() > 1;
 
     // Initialize fields
-    this.elements = new ArrayList(elements);
-
-    ListIterator i = this.elements.listIterator();
-
-    while (i.hasNext()) {
-      Object o = i.next();
-
-      assert o != null;
-      if (o instanceof ConstraintExpression ||
-          o instanceof Constraint) {
-        i.set(o);
-      } else {
-        logger.error("Bad element: "+o.getClass()+" in "+getClass());
-        throw new Error("Bad element: " + o.getClass());
-      }
-    }
+    this.elements = new ArrayList<ConstraintExpression>(elements);
   }
 
 
@@ -147,7 +124,7 @@
    *
    * @return a list of {@link ConstraintExpression}s
    */
-  public List getElements() {
+  public List<ConstraintExpression> getElements() {
     return Collections.unmodifiableList(elements);
   }
 
@@ -168,21 +145,15 @@
    * @return equality.
    */
   public boolean equals(Object o) {
-    if (!super.equals(o)) {
-      return false;
-    }
+    if (!super.equals(o)) return false;
 
     ConstraintOperation co = (ConstraintOperation) o;
-    if (elements.size() != co.elements.size()) {
-      return false;
-    }
+    if (elements.size() != co.elements.size()) return false;
 
-    Iterator lhs = elements.iterator();
-    Iterator rhs = co.elements.iterator();
+    Iterator<ConstraintExpression> lhs = elements.iterator();
+    Iterator<ConstraintExpression> rhs = co.elements.iterator();
     while (lhs.hasNext()) {
-      if (!(lhs.next().equals(rhs.next()))) {
-        return false;
-      }
+      if (!(lhs.next().equals(rhs.next()))) return false;
     }
 
     return true;
@@ -194,18 +165,12 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
+  public Set<Variable> getVariables() {
     // Check to see if there variables have been retrieved.
     if (variables == null) {
-      Set v = new HashSet();
+      Set<Variable> v = new HashSet<Variable>();
 
-      for (Iterator it = getElements().iterator(); it.hasNext(); ) {
-        // Get the operands and check to see if they are a valid constraint.
-        Object e = it.next();
-        if (e instanceof ConstraintExpression) {
-          v.addAll(((ConstraintExpression)e).getVariables());
-        }
-      }
+      for (ConstraintExpression expr: getElements()) v.addAll(expr.getVariables());
 
       variables = Collections.unmodifiableSet(v);
     }
@@ -221,10 +186,8 @@
    */
   public int hashCode() {
     int hashCode = 0;
-    Iterator i = elements.iterator();
-    while (i.hasNext()) {
-      hashCode ^= i.next().hashCode();
-    }
+    Iterator<ConstraintExpression> i = elements.iterator();
+    while (i.hasNext()) hashCode ^= i.next().hashCode();
     return hashCode;
   }
 
@@ -235,13 +198,11 @@
    */
   public String toString() {
     StringBuffer buffer = new StringBuffer("(" + getName());
-    Iterator i = getElements().iterator();
+    Iterator<ConstraintExpression> i = getElements().iterator();
 
     while (i.hasNext()) {
       buffer.append(i.next().toString());
-      if (i.hasNext()) {
-        buffer.append(" ");
-      }
+      if (i.hasNext()) buffer.append(" ");
     }
 
     buffer.append(")");

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintTrue.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintTrue.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ConstraintTrue.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -99,8 +99,8 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
-    return new HashSet();
+  public Set<Variable> getVariables() {
+    return new HashSet<Variable>();
   }
 
   //
@@ -108,14 +108,14 @@
   //
 
   /**
-   * METHOD TO DO
+   * Converts an expression to be made against a new source. In this case, nothing need change.
    *
-   * @param modelExpression PARAMETER TO DO
-   * @param transformation PARAMETER TO DO
-   * @param modelProperty PARAMETER TO DO
-   * @param systemModel PARAMETER TO DO
-   * @param variableFactory PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
+   * @param modelExpression ignored
+   * @param transformation ignored
+   * @param modelProperty ignored
+   * @param systemModel ignored
+   * @param variableFactory ignored
+   * @return The current constraint.
    */
   public ConstraintExpression from(ModelExpression modelExpression,
       Transformation transformation, Value modelProperty, Value systemModel,

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelExpression.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelExpression.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelExpression.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -67,7 +67,7 @@
    *
    * @return a set containing the {@link URI}s of the databases
    */
-  public Set getDatabaseURIs();
+  public Set<URI> getDatabaseURIs();
 
   /**
    * Clones sets of models in the rhs and lhs objects.

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelLiteral.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelLiteral.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelLiteral.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -122,9 +122,10 @@
   /**
    * @return an empty {@link Set}
    */
-  public Set getDatabaseURIs() {
+  @SuppressWarnings("unchecked")
+  public Set<URI> getDatabaseURIs() {
 
-    return Collections.EMPTY_SET;
+    return (Set<URI>)Collections.EMPTY_SET;
   }
 
   //

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelOperation.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelOperation.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelOperation.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -28,6 +28,7 @@
 package org.mulgara.query;
 
 // Java 2 standard packages
+import java.net.URI;
 import java.util.*;
 
 /**
@@ -110,9 +111,9 @@
    *
    * @return The DatabaseURIs value
    */
-  public Set getDatabaseURIs() {
+  public Set<URI> getDatabaseURIs() {
 
-    Set databaseURIs = new HashSet();
+    Set<URI> databaseURIs = new HashSet<URI>();
     databaseURIs.addAll(lhs.getDatabaseURIs());
     databaseURIs.addAll(rhs.getDatabaseURIs());
 
@@ -144,64 +145,61 @@
   }
 
   /**
-   * METHOD TO DO
+   * Transform to an equivalent WHERE clause expression.
    *
-   * @param m PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
+   * @param m The object to compare against.
+   * @return <code>true</code> if the objects are the same type,
+   *         and applied to the same operands 
    */
   public boolean equals(Object m) {
-    if (m == null) return false;
+    
+    if (!(m instanceof ModelOperation)) return false;
+    if ((m == null) || !m.getClass().equals(getClass())) return false;
     if (m == this) return true;
 
     Class<?> type = m.getClass();
-    if (!type.equals(getClass())) return false;
 
+    Set<ModelExpression> otherExpressions = new HashSet<ModelExpression>();
+    ((ModelOperation)m).flattenExpression(otherExpressions, type);
 
-    Set otherExpressions = new HashSet();
-    ( (ModelOperation) m).flattenExpression(otherExpressions, type);
-
-    Set myExpressions = new HashSet();
+    Set<ModelExpression> myExpressions = new HashSet<ModelExpression>();
     flattenExpression(myExpressions, type);
 
     return myExpressions.equals(otherExpressions);
   }
 
   /**
-   * METHOD TO DO
+   * Creates a hash code, based on the child expressions and the current operation type.
    *
-   * @return RETURNED VALUE TO DO
+   * @return The hash code for this object.
    */
   public int hashCode() {
 
-    Set myExpressions = new HashSet();
+    Set<ModelExpression> myExpressions = new HashSet<ModelExpression>();
     flattenExpression(myExpressions, getClass());
 
     return (getClass().hashCode() * 7) + myExpressions.hashCode();
   }
 
   /**
-   * METHOD TO DO
+   * Traverse down the binary tree of the current object, and merge any nodes
+   * of the current type into a flattened set.
    *
-   * @param expressions PARAMETER TO DO
-   * @param type PARAMETER TO DO
+   * @param expressions The set to be built up containing all nodes being
+   *        operated on in the same way.
+   * @param type The class representing the operation type.
    */
-  private void flattenExpression(Set expressions, Class type) {
+  private void flattenExpression(Set<ModelExpression> expressions, Class<?> type) {
 
     if (lhs.getClass().equals(type)) {
-
-      ( (ModelOperation) lhs).flattenExpression(expressions, type);
-    }
-    else {
-
+      ((ModelOperation)lhs).flattenExpression(expressions, type);
+    } else {
       expressions.add(lhs);
     }
 
     if (rhs.getClass().equals(type)) {
-
-      ( (ModelOperation) rhs).flattenExpression(expressions, type);
-    }
-    else {
-
+      ((ModelOperation)rhs).flattenExpression(expressions, type);
+    } else {
       expressions.add(rhs);
     }
   }
@@ -212,20 +210,16 @@
   public Object clone() {
 
     try {
+      ModelOperation cloned = (ModelOperation)super.clone();
 
-      ModelOperation cloned = (ModelOperation) super.clone();
-
       // Copy database URIs.
-      cloned.lhs = (ModelExpression) lhs.clone();
-      cloned.rhs = (ModelExpression) rhs.clone();
+      cloned.lhs = (ModelExpression)lhs.clone();
+      cloned.rhs = (ModelExpression)rhs.clone();
 
       return cloned;
+    } catch (CloneNotSupportedException e) {
+      throw new RuntimeException("ModelOperation subclass " + getClass() + " not cloneable");
     }
-    catch (CloneNotSupportedException e) {
-      throw new RuntimeException(
-          "ModelOperation subclass " + getClass() + " not cloneable"
-          );
-    }
   }
 
 

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelResource.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelResource.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/ModelResource.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -107,7 +107,8 @@
    *   the server if this is a Java RMI or BEEP model, or the empty {@link Set}
    *   otherwise
    */
-  public Set getDatabaseURIs() {
+  @SuppressWarnings("unchecked")
+  public Set<URI> getDatabaseURIs() {
 
     try {
 
@@ -121,18 +122,13 @@
                                              uri.getPath(),
                                              null,
                                              null));
+      } else {
+        return (Set<URI>)Collections.EMPTY_SET;
       }
-      else {
-
-        return Collections.EMPTY_SET;
-      }
+    } catch (URISyntaxException e) {
+      throw new RuntimeException("Couldn't truncate model URI " + uri + " to obtain a database URI");
     }
-    catch (URISyntaxException e) {
 
-      throw new RuntimeException("Couldn't truncate model URI " + uri +
-          " to obtain a database URI");
-    }
-
   }
 
   //

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/Query.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/Query.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/Query.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -29,10 +29,14 @@
 
 // Java 2 standard packages;
 import java.io.*;
+import java.net.URI;
 import java.util.*;
 
 // Third party packages
+
 import org.apache.log4j.*;
+import org.mulgara.connection.Connection;
+import org.mulgara.query.operation.Command;
 
 /**
  * An ITQL query. This is a data structure used as an argument to the
@@ -42,12 +46,6 @@
  *
  * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
  *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:20 $
- *
- * @maintenanceAuthor $Author: newmana $
- *
  * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
  *
  * @copyright &copy; 2001-2003 <A href="http://www.PIsoftware.com/">Plugged In
@@ -55,20 +53,17 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
-public class Query implements Cloneable, Serializable {
+public class Query implements Cloneable, Serializable, Command {
 
  /**
   * Allow newer compiled version of the stub to operate when changes
   * have not occurred with the class.
   * NOTE : update this serialVersionUID when a method or a public member is
   * deleted.
-  * NOTE: Incremented UID to reflect removal of relatedTo.
   */
-  static final long serialVersionUID = 7973523792022156621L;
+  private static final long serialVersionUID = 5165341858790210479L;
 
-  /**
-   * Logger.
-   */
+  /** Logger. */
   private static Logger logger = Logger.getLogger(Query.class.getName());
 
   /**
@@ -77,29 +72,21 @@
    * that there is no <code>select</code> clause and that no projection will be
    * performed.
    */
-  private List variableList;
+  private List<SelectElement> variableList;
 
   /**
    * Mutable version of the variable list. This isn't exposed via {@link
    * #getVariableList} the way {@link #variableList} is.
    */
-  private List mutableVariableList;
+  private List<SelectElement> mutableVariableList;
 
-  /**
-   * The model expression.
-   *
-   * It corresponds to the <code>from</code> clause.
-   */
+  /** The model expression. It corresponds to the <code>from</code> clause. */
   private ModelExpression modelExpression;
 
-  /**
-   * The constraint expression.  It corresponds to the <code>where</code> clause.
-   */
+  /** The constraint expression.  It corresponds to the <code>where</code> clause. */
   private ConstraintExpression constraintExpression;
 
-  /**
-   * The having expression.  It corresponds to the <code>having</code> clause.
-   */
+  /** The having expression.  It corresponds to the <code>having</code> clause. */
   private ConstraintHaving havingConstraint;
 
   /**
@@ -107,7 +94,7 @@
    * major orderings preceding minor orderings. It's only sensible for this to
    * contain orders on variables in the {@link #variableList}.
    */
-  private List orderList;
+  private List<Order> orderList;
 
   /**
    * The limit on rows in the result. If this is <code>null</code>, it indicates
@@ -115,17 +102,15 @@
    */
   private Integer limit;
 
-  /**
-   * The offset on rows in the result. This value is never negative.
-   */
+  /** The offset on rows in the result. This value is never negative. */
   private int offset;
 
-  /**
-   * The accumulated solutions. This can be <code>null</code>, indicating no
-   * solutions.
-   */
+  /** The accumulated solutions. This can be <code>null</code>, indicating no solutions. */
   private Answer answer;
 
+  /** A UI message describing the result of this message. */
+  private String resultMessage = "";
+
   //
   // Constructors
   //
@@ -135,15 +120,16 @@
    *
    * @param variableList {@link Variable}s or node values to appear as bindings
    *     in the solution (i.e. columns of the result {@link Answer});
-   *     <code>null</code> indicates that all columns are to be retained
+   *     <code>null</code> indicates that all columns are to be retained.
+   *     This is a list of: Variable; ConstantValue; Count; Subquery.
    * @param modelExpression an expression defining the model to query, never
    *     <code>null</code>
    * @param constraintExpression an expression defining the constraints to
    *     satisfy, never <code>null</code>
    * @param havingExpression an expression defining the conditions to apply to
    *     aggregate functions or null if not given.
-   * @param orderList sort order column names, currently a list of {@link
-   *     Variable}s with the order assumed to be ascending in all cases
+   * @param orderList sort order column names. This is a list of {@link Order}s
+   *     which is a wrapper around Variable, with an "ascending" flag.
    * @param limit the maximum number of rows to return, which must be
    *     non-negative; <code>null</code> indicates no limit
    * @param offset the number of rows to skip from the beginning of the result,
@@ -156,9 +142,9 @@
    *     <var>constraintExpression</var>, <var>orderList<var> or
    *     <var>answer</var> are <code>null</code>
    */
-  public Query(List variableList, ModelExpression modelExpression,
+  public Query(List<? extends SelectElement> variableList, ModelExpression modelExpression,
       ConstraintExpression constraintExpression,
-      ConstraintHaving havingExpression, List orderList, Integer limit,
+      ConstraintHaving havingExpression, List<Order> orderList, Integer limit,
       int offset, Answer answer) {
 
     // Validate parameters
@@ -175,14 +161,12 @@
     } else if (answer == null) {
       throw new IllegalArgumentException("Null \"answer\" parameter");
     } else if (variableList != null) {
-      Set variableSet = new HashSet(constraintExpression.getVariables());
+      Set<Variable> variableSet = new HashSet<Variable>(constraintExpression.getVariables());
       variableSet.addAll(Arrays.asList(answer.getVariables()));
 
-      Iterator i = variableList.iterator();
-      while (i.hasNext()) {
-        Object o = i.next();
+      for (Object o: variableList) {
         if (o instanceof Variable) {
-          Variable var = (Variable) o;
+          Variable var = (Variable)o;
           if (!variableSet.contains(var)) {
             logger.warn("Failed to find " + var + " in " + variableSet);
             throw new IllegalArgumentException("Failed to constrain all variables: " + var +
@@ -193,15 +177,12 @@
     }
 
     // Initialize fields
-    this.mutableVariableList =
-        (variableList == null) ? null : new ArrayList(variableList);
-    this.variableList =
-        (variableList == null) ? null
-        : Collections.unmodifiableList(mutableVariableList);
+    this.mutableVariableList = (variableList == null) ? null : new ArrayList<SelectElement>(variableList);
+    this.variableList = (variableList == null) ? null : Collections.unmodifiableList(mutableVariableList);
     this.modelExpression = modelExpression;
     this.constraintExpression = constraintExpression;
     this.havingConstraint = havingExpression;
-    this.orderList = Collections.unmodifiableList(new ArrayList(orderList));
+    this.orderList = Collections.unmodifiableList(new ArrayList<Order>(orderList));
     this.limit = limit;
     this.offset = offset;
     this.answer = answer;
@@ -252,10 +233,8 @@
       cloned.mutableVariableList = null;
       cloned.variableList = null;
     } else {
-      cloned.variableList = new ArrayList();
-      Iterator i = variableList.iterator();
-      while (i.hasNext()) {
-        Object o = i.next();
+      cloned.variableList = new ArrayList<SelectElement>();
+      for (SelectElement o : variableList) {
         if (o instanceof Subquery) {
           Subquery s = (Subquery)o;
           cloned.variableList.add(new Subquery(s.getVariable(), (Query)s.getQuery().clone()));
@@ -269,7 +248,7 @@
       cloned.mutableVariableList = Collections.unmodifiableList(cloned.variableList);
     }
     cloned.modelExpression = modelExpression;  // FIXME: should be cloned
-    cloned.answer = (Answer) answer.clone();
+    cloned.answer = (Answer)answer.clone();
 
     // Copy immutable fields by reference
     cloned.orderList = orderList;
@@ -286,15 +265,16 @@
   /**
    * Accessor for the <code>variableList</code> property.
    *
-   * @return a {@link List} containing one or more {@link Variable}s
+   * @return a {@link List} containing one or more {@link Variable}s, {@link ContantValue}s,
+   * {@link Count}s or {@link Subquery}
    */
-  public List getVariableList() {
+  public List<SelectElement> getVariableList() {
     return variableList;
   }
 
+
   /**
    * Accessor for the <code>constraintExpression</code> property.
-   *
    * @return a {@link ConstraintExpression}
    */
   public ConstraintExpression getConstraintExpression() {
@@ -302,8 +282,7 @@
   }
 
   /**
-   * Accesor for the <code>havingExpression</code> property.
-   *
+   * Accessor for the <code>havingExpression</code> property.
    * @return a {@link ConstraintExpression} containing only
    *   {@link ConstraintHaving} or <code>null</code> to indicate an empty
    *   having clause.
@@ -312,149 +291,112 @@
     return havingConstraint;
   }
 
+
   /**
    * Accessor for the <code>modelExpression</code> property.
-   *
-   * @return a {@link ModelExpression}, or <code>null</code> to indicate the
-   *      empty model
+   * @return a {@link ModelExpression}, or <code>null</code> to indicate the empty model
    */
   public ModelExpression getModelExpression() {
     return modelExpression;
   }
 
+
   /**
    * Accessor for the <code>orderList</code> property.
-   *
-   * @return a {@link List} containing one or more {@link Variable}s
+   * @return a {@link List} containing one or more {@link Order}s
+   *         (which wrap {@link Variable}s)
    */
-  public List getOrderList() {
+  public List<Order> getOrderList() {
     return orderList;
   }
 
+
   /**
    * Accessor for the <code>limit</code> property.
-   *
    * @return the limit for this query, or <code>null</code> if unlimited
    */
   public Integer getLimit() {
     return limit;
   }
 
+
   /**
    * Accessor for the <code>offset</code> property.
-   *
    * @return the offset for this query, a non-negative integer
    */
   public int getOffset() {
     return offset;
   }
 
+
   /**
    * Accessor for the <code>answer</code> property. If the <var>
    * constraintExpression</var> property is <code>null</code>, this is the
    * answer to the entire query.
-   *
-   * @return an {@link Answer}, or <code>null</code> to indicate the set of all
-   *      statements
+   * @return an {@link Answer}, or <code>null</code> to indicate the set of all statements
    */
   public Answer getGiven() {
     return answer;
   }
 
+
   //
   // Methods overriding Object
   //
 
   /**
    * Equality is by value.
-   *
-   * @param object PARAMETER TO DO
-   * @return RETURNED VALUE TO DO
+   * @param object The object to compare to
+   * @return <code>true</code> if object is functionaly equivalent to this object.
    */
   public boolean equals(Object object) {
 
-    if (object == this) {
+    if (object == this) return true;
+    if (object == null) return false;
+    if (!(object instanceof Query)) return false;
 
-      return true;
-    }
+    Query query = (Query)object;
 
-    if (object == null) {
-
-      return false;
-    }
-
-    if (! (object instanceof Query)) {
-
-      return false;
-    }
-
-    Query query = (Query) object;
-
     // Check the variableList field
-    if (!variableList.equals(query.variableList)) {
+    if (!variableList.equals(query.variableList)) return false;
 
-      return false;
-    }
-
     // Check the modelExpression field
-    if ( (modelExpression == null) ? (query.modelExpression != null)
-        : (!modelExpression.equals(
-        query.modelExpression))) {
-
+    if ((modelExpression == null) ?
+        (query.modelExpression != null) :
+        (!modelExpression.equals(query.modelExpression))) {
       return false;
     }
 
     // Check the constraintExpression field
-    if ((constraintExpression == null) ? (query.constraintExpression != null)
-        : (!constraintExpression.equals(query.constraintExpression))) {
-
+    if ((constraintExpression == null) ?
+        (query.constraintExpression != null) :
+        (!constraintExpression.equals(query.constraintExpression))) {
       return false;
     }
 
-    if ((havingConstraint == null) ? (query.havingConstraint != null)
-        : (!havingConstraint.equals(query.havingConstraint))) {
-
+    if ((havingConstraint == null) ?
+        (query.havingConstraint != null) :
+        (!havingConstraint.equals(query.havingConstraint))) {
       return false;
     }
 
     // Check the orderList field
-    if ( (orderList == null) ^ (query.orderList == null)) {
+    if ((orderList == null) ^ (query.orderList == null)) return false;
 
-      return false;
-    }
+    if ((orderList != null) && !orderList.equals(query.orderList)) return false;
 
-    if ( (orderList != null) && !orderList.equals(query.orderList)) {
-
-      return false;
-    }
-
     // Check the limit field
-    if ( (limit == null) ^ (query.limit == null)) {
+    if ((limit == null) ^ (query.limit == null)) return false;
+    if ((limit != null) && !limit.equals(query.limit)) return false;
 
-      return false;
-    }
-
-    if ( (limit != null) && !limit.equals(query.limit)) {
-
-      return false;
-    }
-
     // Check the offset field
-    if (offset != query.offset) {
+    if (offset != query.offset) return false;
 
-      return false;
-    }
-
-    // Check the answer field
-    if (!answer.equals(query.answer)) {
-
-      return false;
-    }
-
-    // All checks passed, so the object is equal
-    return true;
+    // Finally, it comes down to the answer field
+    return answer.equals(query.answer);
   }
 
+
   /**
    * Close this {@link Query}, and the underlying {@link Answer} objects.
    */
@@ -463,34 +405,27 @@
     answer = null;
 
     if (mutableVariableList != null) {
-      Iterator it = mutableVariableList.iterator();
-      while (it.hasNext()) {
-        Object v = it.next();
-        if (v instanceof AggregateFunction)
+      for (SelectElement v: mutableVariableList) {
+        if (v instanceof AggregateFunction) {
           ((AggregateFunction)v).getQuery().close();
+        }
       }
     }
   }
 
+
   /**
    * Generate a legible representation of the query.
    *
-   * @return RETURNED VALUE TO DO
+   * @return A string representing all the elements of a query.
    */
   public String toString() {
-
     StringBuffer buffer = new StringBuffer();
 
     // SELECT
     if (variableList != null) {
-
       buffer.append("SELECT");
-
-      for (Iterator i = variableList.iterator(); i.hasNext(); ) {
-
-        buffer.append(" ").append(i.next());
-      }
-
+      for (Object i: variableList) buffer.append(" ").append(i);
       buffer.append(" ");
     }
 
@@ -501,46 +436,29 @@
     buffer.append(" WHERE ").append(constraintExpression);
 
     // HAVING
-    if (havingConstraint != null) {
-      buffer.append(" HAVING ").append(havingConstraint);
-    }
+    if (havingConstraint != null) buffer.append(" HAVING ").append(havingConstraint);
 
     // ORDER BY
     if (!orderList.isEmpty()) {
-
       buffer.append(" ORDER BY");
-
-      for (Iterator i = orderList.iterator(); i.hasNext(); ) {
-
-        buffer.append(" ").append(i.next());
-      }
+      for (Order o: orderList) buffer.append(" ").append(o);
     }
 
     // LIMIT
-    if (limit != null) {
+    if (limit != null) buffer.append(" LIMIT ").append(limit.intValue());
 
-      buffer.append(" LIMIT ").append(limit.intValue());
-    }
-
     // OFFSET
-    if (offset != 0) {
+    if (offset != 0) buffer.append(" OFFSET ").append(offset);
 
-      buffer.append(" OFFSET ").append(offset);
-    }
-
     // GIVEN
-    if (answer != null) {
+    if (answer != null) buffer.append(" GIVEN ").append(answer);
 
-      buffer.append(" GIVEN ").append(answer);
-    }
-
     return buffer.toString();
   }
 
 
   /**
    * Serializes the current object to a stream.
-   *
    * @param out The stream to write to.
    * @throws IOException If an I/O error occurs while writing.
    */
@@ -558,4 +476,81 @@
     }
     out.defaultWriteObject();
   }
+
+
+  //
+  // Command interface methods
+  //
+  
+  /**
+   * Operation can only be run by a server.
+   * @return <code>false</code> as this is AST for a server.
+   */
+  public boolean isLocalOperation() {
+    return false;
+  }
+
+
+  /**
+   * Operation is not restricted to a user interface.
+   * @return <code>false</code> as this operation has no effect on a UI.
+   */
+  public boolean isUICommand() {
+    return false;
+  }
+
+
+  /**
+   * Indicates that this command returns an Answer. Saves the overhead of checking
+   * the return type of execute.
+   * @return <code>true</code>.
+   */
+  public boolean isAnswerable() {
+    return true;
+  }
+
+
+  /**
+   * Indicates that the command modifies the state in a transaction.
+   * @return <code>true</code> If the transaction state is to be modified.
+   */
+  public boolean isTxCommitRollback() {
+    return false;
+  }
+  
+  /**
+   * Gets the associated server for a non-local operation.
+   * @return the server URI, or <code>null</code> if the data should be found locally.
+   */
+  public URI getServerURI() {
+    Set<URI> dbURIs = getModelExpression().getDatabaseURIs();
+    return dbURIs.isEmpty() ? null : dbURIs.iterator().next();
+  }
+
+
+  /**
+   * Gets a message text relevant to the operation.  Useful for the UI.
+   * Consider changing this to a serialization of the result.
+   * @return A text message associated with the result of this operation. Usually empty.
+   */
+  public String getResultMessage() {
+    return resultMessage;
+  }
+
+
+  /**
+   * Executes this query on a connection.
+   * @param conn The connection to a database session to execute the query against.
+   * @return The answer to this query.  This must be closed by the calling code.
+   */
+  public Object execute(Connection conn) throws QueryException, TuplesException {
+    if (logger.isDebugEnabled()) logger.debug("Executing query " + toString());
+    Answer answer = conn.getSession().query(this);
+    if (answer == null) throw new QueryException("Invalid answer received");
+    if (logger.isDebugEnabled()) logger.debug("Successfully executed query");
+    // move to the first row
+    answer.beforeFirst();
+    return answer;
+  }
+
 }

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/QueryUnitTest.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/QueryUnitTest.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/QueryUnitTest.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -35,7 +35,7 @@
 import java.util.*;
 
 // Log4J
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 // Locally written packages.
 import org.mulgara.query.rdf.LiteralImpl;
@@ -45,18 +45,8 @@
  * Purpose: Test case for {@link Query}.
  *
  * @created 2001-10-23
- *
  * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
- *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:20 $ by $Author: newmana $
- *
- * @maintenanceAuthor $Author: newmana $
- *
- * @copyright &copy;2001-2004
- *   <a href="http://www.pisoftware.com/">Plugged In Software Pty Ltd</a>
- *
+ * @copyright &copy;2001-2004 <a href="http://www.pisoftware.com/">Plugged In Software Pty Ltd</a>
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
 public class QueryUnitTest extends TestCase {
@@ -66,10 +56,8 @@
    */
   private Query query;
 
-  /**
-   * Logger.
-   */
-  private Category logger = Category.getInstance(QueryUnitTest.class.getName());
+  // /** Logger. */
+  // private Category logger = Category.getInstance(QueryUnitTest.class.getName());
 
   /**
    * Constructs a new answer test with the given name.
@@ -86,7 +74,6 @@
    * @return The test suite
    */
   public static Test suite() {
-
     TestSuite suite = new TestSuite();
 
     suite.addTest(new QueryUnitTest("test1Equals"));
@@ -102,7 +89,6 @@
    * @param args the command line arguments
    */
   public static void main(String[] args) {
-
     junit.textui.TestRunner.run(suite());
   }
 
@@ -111,17 +97,16 @@
    *
    * @throws Exception EXCEPTION TO DO
    */
+  @SuppressWarnings("unchecked")
   public void setUp() throws Exception {
-
     query = new Query(
-        Arrays.asList(new Variable[] {
-        new Variable("x")}),                    // variable list
+        Arrays.asList(new SelectElement[] { new Variable("x") }), // variable list
         new ModelResource(new URI("x:m")),      // model expression
         new ConstraintImpl(new Variable("x"),   // constraint expression
         new URIReferenceImpl(new URI("x:p")),
         new LiteralImpl("o")),
         null,                                   // no having
-        Collections.EMPTY_LIST,                 // no ordering
+        (List<Order>)Collections.EMPTY_LIST,    // no ordering
         null,                                   // no limit
         0,                                      // zero offset
         new UnconstrainedAnswer());
@@ -137,7 +122,6 @@
    * @throws Exception if query fails when it should have succeeded
    */
   public void testClone() throws Exception {
-
     Query copied = (Query) query.clone();
     assertTrue(copied != query);
     assertEquals(copied, query);
@@ -149,9 +133,7 @@
    * @throws Exception if query fails when it should have succeeded
    */
   public void test1Equals() throws Exception {
-
     Query query2 = query;
-
     assertTrue(query.equals(query2));
   }
 
@@ -160,18 +142,17 @@
    *
    * @throws Exception if query fails when it should have succeeded
    */
+  @SuppressWarnings("unchecked")
   public void test2Equals() throws Exception {
-
     // Compose test instances
     Query query2 = new Query(
-        Arrays.asList(new Variable[] {
-        new Variable("x")}),                    // variable list
+        Arrays.asList(new SelectElement[] { new Variable("x") }), // variable list
         new ModelResource(new URI("x:m")),      // model expression
         new ConstraintImpl(new Variable("x"),   // constraint expression
         new URIReferenceImpl(new URI("x:p")),
         new LiteralImpl("o")),
         null,                                  // no having
-        Collections.EMPTY_LIST,                // no ordering
+        (List<Order>)Collections.EMPTY_LIST,   // no ordering
         null,                                  // no limit
         0,                                     // zero offset
         new UnconstrainedAnswer());
@@ -188,7 +169,6 @@
    * @throws Exception if query fails when it should have succeeded
    */
   public void test3Equals() throws Exception {
-
     assertTrue(!query.equals(null));
   }
 }

Added: branches/mgr-73/src/jar/query/java/org/mulgara/query/SelectElement.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/SelectElement.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/SelectElement.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,30 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.rosenlaw.com/OSL3.0.htm
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * This file is an original work developed by Netymon Pty Ltd
+ * (http://www.netymon.com, mailto:mail at netymon.com). Portions created
+ * by Netymon Pty Ltd are Copyright (c) 2006 Netymon Pty Ltd.
+ * All Rights Reserved.
+ */
+package org.mulgara.query;
+
+import java.io.Serializable;
+
+/**
+ * Exception to indicate a failure within the transaction handling.
+ *
+ * @created 2008-01-14
+ * @author <a href="mailto:andrae at netymon.com">Andrae Muys</a>
+ * @company <A href="mailto:mail at netymon.com">Netymon Pty Ltd</A>
+ * @copyright &copy;2008 <a href="http://www.topazproject.org/">The Topaz * Foundation</a>
+ * @licence Open Software License v3.0</a>
+ */
+public interface SelectElement extends Serializable, Cloneable { }

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/SingleTransitiveConstraint.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/SingleTransitiveConstraint.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/SingleTransitiveConstraint.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -33,7 +33,7 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 /**
  * A transitive constraint. The elements within the constraint must be variable
@@ -68,11 +68,8 @@
    */
   static final long serialVersionUID = -3828723182891026790L;
 
-  /**
-   * Logger.
-   */
-  private final static Category logger =
-      Category.getInstance(Constraint.class.getName());
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(Constraint.class.getName());
 
   /**
    * The constraint containing the transitive predicate.
@@ -140,7 +137,7 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
+  public Set<Variable> getVariables() {
     return transConstraint.getVariables();
   }
 

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/SpecialPredicates.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/SpecialPredicates.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/SpecialPredicates.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -29,14 +29,13 @@
 
 // java packages
 import java.net.URI;
-import java.net.URISyntaxException;
+import java.util.Set;
 
 // external packages
-import org.jrdf.graph.URIReference;
 import org.jrdf.vocabulary.Vocabulary;
 
 // local packages
-import org.mulgara.query.rdf.Mulgara;
+import static org.mulgara.query.rdf.Mulgara.NAMESPACE;
 
 /**
  * Provides a central point for defining all magic predicates used by Mulgara.
@@ -57,22 +56,23 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
+ at SuppressWarnings({ "serial", "unchecked" })
 public class SpecialPredicates extends Vocabulary {
 
   /** The string for the equality predicate */
-  public static final String IS = Mulgara.NAMESPACE + "is";
+  public static final String IS = NAMESPACE + "is";
 
   /** The string for the cardinality equality predicate */
-  public static final String OCCURS = Mulgara.NAMESPACE + "occurs";
+  public static final String OCCURS = NAMESPACE + "occurs";
 
   /** The string for the cardinality equality predicate */
-  public static final String NOT_OCCURS = Mulgara.NAMESPACE + "notOccurs";
+  public static final String NOT_OCCURS = NAMESPACE + "notOccurs";
 
   /** The string for the cardinality less than predicate */
-  public static final String OCCURS_LESS_THAN = Mulgara.NAMESPACE + "occursLessThan";
+  public static final String OCCURS_LESS_THAN = NAMESPACE + "occursLessThan";
 
   /** The string for the cardinality greater than predicate */
-  public static final String OCCURS_MORE_THAN = Mulgara.NAMESPACE + "occursMoreThan";
+  public static final String OCCURS_MORE_THAN = NAMESPACE + "occursMoreThan";
 
   /** The URI for the equality predicate */
   public static final URI MULGARA_IS;
@@ -91,22 +91,17 @@
 
   // intialize all predicate URIs
   static {
-    try {
-      MULGARA_IS = new URI(IS);
-      MULGARA_OCCURS = new URI(OCCURS);
-      MULGARA_NOT_OCCURS = new URI(NOT_OCCURS);
-      MULGARA_OCCURS_LESS_THAN = new URI(OCCURS_LESS_THAN);
-      MULGARA_OCCURS_MORE_THAN = new URI(OCCURS_MORE_THAN);
+    MULGARA_IS = URI.create(IS);
+    MULGARA_OCCURS = URI.create(OCCURS);
+    MULGARA_NOT_OCCURS = URI.create(NOT_OCCURS);
+    MULGARA_OCCURS_LESS_THAN = URI.create(OCCURS_LESS_THAN);
+    MULGARA_OCCURS_MORE_THAN = URI.create(OCCURS_MORE_THAN);
 
-      resources.add(MULGARA_IS);
-      resources.add(MULGARA_OCCURS);
-      resources.add(MULGARA_NOT_OCCURS);
-      resources.add(MULGARA_OCCURS_LESS_THAN);
-      resources.add(MULGARA_OCCURS_MORE_THAN);
-    } catch (URISyntaxException e) {
-      // Houston, we have a problem.  Not much we can do with it, so rethrow as an error.
-      throw new ExceptionInInitializerError(e);
-    }
+    ((Set<URI>)resources).add(MULGARA_IS);
+    ((Set<URI>)resources).add(MULGARA_OCCURS);
+    ((Set<URI>)resources).add(MULGARA_NOT_OCCURS);
+    ((Set<URI>)resources).add(MULGARA_OCCURS_LESS_THAN);
+    ((Set<URI>)resources).add(MULGARA_OCCURS_MORE_THAN);
   }
 
 

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/TransitiveConstraint.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/TransitiveConstraint.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/TransitiveConstraint.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -33,7 +33,7 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 /**
  * A transitive constraint.  The constraint must take the form of an anchored
@@ -68,11 +68,8 @@
    */
   static final long serialVersionUID = -3828723182891026790L;
 
-  /**
-   * Logger.
-   */
-  private final static Category logger =
-      Category.getInstance(Constraint.class.getName());
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(Constraint.class.getName());
 
   /**
    * The constraint containing the anchored transitive predicate.
@@ -174,8 +171,8 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
-    Set vars = new HashSet();
+  public Set<Variable> getVariables() {
+    Set<Variable> vars = new HashSet<Variable>();
     vars.addAll(unanchoredConstraint.getVariables());
     vars.addAll(anchoredConstraint.getVariables());
     return vars;

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/Variable.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/Variable.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/Variable.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -45,7 +45,7 @@
  *
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
  */
-public class Variable implements ConstraintElement {
+public class Variable implements SelectElement, ConstraintElement {
 
   /**
    * Allow newer compiled version of the stub to operate when changes

Modified: branches/mgr-73/src/jar/query/java/org/mulgara/query/WalkConstraint.java
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/WalkConstraint.java	2008-01-10 15:02:00 UTC (rev 621)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/WalkConstraint.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -33,7 +33,7 @@
 import java.util.*;
 
 // Third party packages
-import org.apache.log4j.Category;
+// import org.apache.log4j.Category;
 
 /**
  * A walk constraint. The constraint must take the form of an anchored
@@ -67,11 +67,8 @@
    */
   static final long serialVersionUID = 1054509776341736706L;
 
-  /**
-   * Logger.
-   */
-  private final static Category logger =
-      Category.getInstance(Constraint.class.getName());
+  // /** Logger. */
+  // private final static Category logger = Category.getInstance(Constraint.class.getName());
 
   /**
    * The constraint containing the anchored constraint.
@@ -147,8 +144,8 @@
    *
    * @return A set containing all variable constraints.
    */
-  public Set getVariables() {
-    Set vars = new HashSet();
+  public Set<Variable> getVariables() {
+    Set<Variable> vars = new HashSet<Variable>();
     vars.addAll(unanchoredConstraint.getVariables());
     vars.addAll(anchoredConstraint.getVariables());
     return vars;

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation)

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/AddAlias.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/AddAlias.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/AddAlias.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,75 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-
-package org.mulgara.query.operation;
-
-import org.mulgara.connection.Connection;
-
-
-/**
- * An AST element for the ALIAS command.
- *
- * @created 2007-11-14
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class AddAlias extends LocalCommand {
-  
-  private static final String SUCCESS_MSG_PREFIX = "Successfully aliased ";
-
-  private static final String SUCCESS_MSG_AS = " as ";
-
-  /** The new alias to set. */
-  private final String aliasPrefix;
-  
-  /** The string for the URI of the alias. */
-  private final String aliasTarget;
-
-  /**
-   * Creates a new alias command.
-   * @param aliasPrefix The alias to set.
-   * @param aliasTarget The URI that the alias applies to.
-   */
-  public AddAlias(String aliasPrefix, String aliasTarget) {
-    this.aliasPrefix = aliasPrefix;
-    this.aliasTarget = aliasTarget;
-  }
-  
-  /**
-   * Indicates that this operation is for a UI.
-   * @return <code>true</code> as operation is for UI output only.
-   */
-  public boolean isUICommand() {
-    return true;
-  }
-
-  /** @return the aliasPrefix */
-  public String getAliasPrefix() {
-    return aliasPrefix;
-  }
-
-  /** @return the aliasTarget */
-  public String getAliasTarget() {
-    return aliasTarget;
-  }
-
-  /**
-   * Asks for the help text associated with the creation of this object.
-   * @param conn ignored.
-   * @return The text of the help request.
-   */
-  public Object execute(Connection conn) throws Exception {
-    return setResultMessage(SUCCESS_MSG_PREFIX + aliasTarget + SUCCESS_MSG_AS + aliasPrefix);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/AddAlias.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/AddAlias.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/AddAlias.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/AddAlias.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,75 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.query.operation;
+
+import org.mulgara.connection.Connection;
+
+
+/**
+ * An AST element for the ALIAS command.
+ *
+ * @created 2007-11-14
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class AddAlias extends LocalCommand {
+  
+  private static final String SUCCESS_MSG_PREFIX = "Successfully aliased ";
+
+  private static final String SUCCESS_MSG_AS = " as ";
+
+  /** The new alias to set. */
+  private final String aliasPrefix;
+  
+  /** The string for the URI of the alias. */
+  private final String aliasTarget;
+
+  /**
+   * Creates a new alias command.
+   * @param aliasPrefix The alias to set.
+   * @param aliasTarget The URI that the alias applies to.
+   */
+  public AddAlias(String aliasPrefix, String aliasTarget) {
+    this.aliasPrefix = aliasPrefix;
+    this.aliasTarget = aliasTarget;
+  }
+  
+  /**
+   * Indicates that this operation is for a UI.
+   * @return <code>true</code> as operation is for UI output only.
+   */
+  public boolean isUICommand() {
+    return true;
+  }
+
+  /** @return the aliasPrefix */
+  public String getAliasPrefix() {
+    return aliasPrefix;
+  }
+
+  /** @return the aliasTarget */
+  public String getAliasTarget() {
+    return aliasTarget;
+  }
+
+  /**
+   * Asks for the help text associated with the creation of this object.
+   * @param conn ignored.
+   * @return The text of the help request.
+   */
+  public Object execute(Connection conn) throws Exception {
+    return setResultMessage(SUCCESS_MSG_PREFIX + aliasTarget + SUCCESS_MSG_AS + aliasPrefix);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,108 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.net.URI;
-import java.rmi.RemoteException;
-
-import org.mulgara.connection.Connection;
-import org.mulgara.query.QueryException;
-import org.mulgara.rules.InitializerException;
-import org.mulgara.rules.RulesException;
-import org.mulgara.rules.RulesRef;
-
-/**
- * Represents a command to apply rules to a set of data.
- *
- * @created Aug 10, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class ApplyRules extends ServerCommand {
-
-  /** The graph containing the rules to be run. */
-  private final URI ruleGraph;
-  
-  /** The graph containing the data to apply the rules to. */
-  private final URI baseGraph;
-  
-  /** The graph to put the rule productions into. */
-  private final URI destGraph;
-  
-  /**
-   * Create a new rules command.
-   * @param ruleGraph The graph containing the rules to be run.
-   * @param baseGraph The graph containing the data to apply the rules to.
-   * @param destGraph The graph to put the rule productions into.
-   */
-  public ApplyRules(URI ruleGraph, URI baseGraph, URI destGraph) {
-    super(destGraph);
-    this.ruleGraph = ruleGraph;
-    this.baseGraph = baseGraph;
-    this.destGraph = destGraph;
-  }
-  
-  /**
-   * @return the ruleGraph
-   */
-  public URI getRuleGraph() {
-    return ruleGraph;
-  }
-
-  /**
-   * @return the baseGraph
-   */
-  public URI getBaseGraph() {
-    return baseGraph;
-  }
-
-  /**
-   * @return the destGraph
-   */
-  public URI getDestGraph() {
-    return destGraph;
-  }
-
-  /**
-   * Apply rules using the given connection.
-   * @param conn The connection to make the rule application on.
-   * @return A string containing the result message.
-   * @throws InitializerException The rules were not structured correctly.
-   * @throws QueryException Unable to read the rules.
-   * @throws RemoteException There was a connectivity problem with the server.
-   * @throws RulesException There was an error with the application of the rules.
-   */
-  public Object execute(Connection conn) throws RemoteException, RulesException, QueryException, InitializerException {
-    return execute(conn, conn);
-  }
-
-  /**
-   * Apply rules using separate connections for getting rules and applying them.
-   * @param conn The connection to apply the rules with.
-   * @param ruleConn The connection to retrieve rules over.
-   * @return A string containing the result message.
-   * @throws InitializerException The rules were not structured correctly.
-   * @throws QueryException Unable to read the rules.
-   * @throws RemoteException There was a connectivity problem with the server.
-   * @throws RulesException There was an error with the application of the rules.
-   */
-  public Object execute(Connection conn, Connection ruleConn) throws RemoteException, RulesException, QueryException, InitializerException {
-    if (conn == null) throw new IllegalArgumentException("Connection may not be null");
-    // get the structure from the rule model
-    RulesRef rules = ruleConn.getSession().buildRules(ruleGraph, baseGraph, destGraph);
-    // create apply the rules to the model
-    conn.getSession().applyRules(rules);
-    return setResultMessage("Successfully applied " + ruleGraph + " to " + baseGraph + (destGraph == baseGraph ? "" : " => " + destGraph));
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ApplyRules.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,108 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.net.URI;
+import java.rmi.RemoteException;
+
+import org.mulgara.connection.Connection;
+import org.mulgara.query.QueryException;
+import org.mulgara.rules.InitializerException;
+import org.mulgara.rules.RulesException;
+import org.mulgara.rules.RulesRef;
+
+/**
+ * Represents a command to apply rules to a set of data.
+ *
+ * @created Aug 10, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class ApplyRules extends ServerCommand {
+
+  /** The graph containing the rules to be run. */
+  private final URI ruleGraph;
+  
+  /** The graph containing the data to apply the rules to. */
+  private final URI baseGraph;
+  
+  /** The graph to put the rule productions into. */
+  private final URI destGraph;
+  
+  /**
+   * Create a new rules command.
+   * @param ruleGraph The graph containing the rules to be run.
+   * @param baseGraph The graph containing the data to apply the rules to.
+   * @param destGraph The graph to put the rule productions into.
+   */
+  public ApplyRules(URI ruleGraph, URI baseGraph, URI destGraph) {
+    super(destGraph);
+    this.ruleGraph = ruleGraph;
+    this.baseGraph = baseGraph;
+    this.destGraph = destGraph;
+  }
+  
+  /**
+   * @return the ruleGraph
+   */
+  public URI getRuleGraph() {
+    return ruleGraph;
+  }
+
+  /**
+   * @return the baseGraph
+   */
+  public URI getBaseGraph() {
+    return baseGraph;
+  }
+
+  /**
+   * @return the destGraph
+   */
+  public URI getDestGraph() {
+    return destGraph;
+  }
+
+  /**
+   * Apply rules using the given connection.
+   * @param conn The connection to make the rule application on.
+   * @return A string containing the result message.
+   * @throws InitializerException The rules were not structured correctly.
+   * @throws QueryException Unable to read the rules.
+   * @throws RemoteException There was a connectivity problem with the server.
+   * @throws RulesException There was an error with the application of the rules.
+   */
+  public Object execute(Connection conn) throws RemoteException, RulesException, QueryException, InitializerException {
+    return execute(conn, conn);
+  }
+
+  /**
+   * Apply rules using separate connections for getting rules and applying them.
+   * @param conn The connection to apply the rules with.
+   * @param ruleConn The connection to retrieve rules over.
+   * @return A string containing the result message.
+   * @throws InitializerException The rules were not structured correctly.
+   * @throws QueryException Unable to read the rules.
+   * @throws RemoteException There was a connectivity problem with the server.
+   * @throws RulesException There was an error with the application of the rules.
+   */
+  public Object execute(Connection conn, Connection ruleConn) throws RemoteException, RulesException, QueryException, InitializerException {
+    if (conn == null) throw new IllegalArgumentException("Connection may not be null");
+    // get the structure from the rule model
+    RulesRef rules = ruleConn.getSession().buildRules(ruleGraph, baseGraph, destGraph);
+    // create apply the rules to the model
+    conn.getSession().applyRules(rules);
+    return setResultMessage("Successfully applied " + ruleGraph + " to " + baseGraph + (destGraph == baseGraph ? "" : " => " + destGraph));
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Backup.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Backup.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Backup.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,160 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.rmi.NoSuchObjectException;
-import java.rmi.RemoteException;
-import java.rmi.server.UnicastRemoteObject;
-
-import org.apache.log4j.Logger;
-import org.mulgara.connection.Connection;
-import org.mulgara.query.QueryException;
-
-import edu.emory.mathcs.util.remote.io.RemoteOutputStream;
-import edu.emory.mathcs.util.remote.io.server.impl.RemoteOutputStreamSrvImpl;
-
-/**
- * Represents a command to back data up from a model.
- *
- * @created Aug 19, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class Backup extends DataTx {
-  
-  private static final String FILE = "file";
-
-  /** The logger */
-  static final Logger logger = Logger.getLogger(Backup.class.getName());
-
-  /** The URI for the server. */
-  private URI serverUri;
-
-  /**
-   * Creates a new Backup command.
-   * @param source The data to back up.  May be a server or just a single graph.
-   * @param destination The location where to back the data up.
-   *        Only file URLs supported at the moment.
-   */
-  public Backup(URI source, URI destination, boolean locality) {
-    super(source, destination, source, locality);
-    if (!destination.getScheme().equals(FILE)) throw new IllegalArgumentException("Backups must be sent to a file");
-    updateServerUri(source);
-  }
-
-  /**
-   * @return The URI of the destination graph.
-   */
-  public URI getServerURI() throws UnsupportedOperationException {
-    return serverUri;
-  }
-
-
-  /**
-   * Perform a backup on a server.
-   * @param conn The connection to talk to the server on.
-   * @return The text describing the server that was backed up.
-   * @throws QueryException There was an error asking the server to perform the backup.
-   * @throws MalformedURLException The destination is not a valid file.
-   */
-  public Object execute(Connection conn) throws QueryException, MalformedURLException {
-    // test if the server can do all the work, or if data needs to be streamed
-    if (isLocal()) {
-      // server does all the work
-      conn.getSession().backup(getSource(), getDestination());
-    } else {
-      // need to stream data through to an output stream
-      FileOutputStream fileOutputStream = null;
-      String destinationFile = this.getDestination().toURL().getPath();
-      try {
-        fileOutputStream = new FileOutputStream(destinationFile);
-      } catch (FileNotFoundException ex) {
-        throw new QueryException("File " + destinationFile + " cannot be created for backup. ", ex);
-      }
-
-      // send to open method for backing up to a stream
-      backup(conn, getSource(), fileOutputStream);
-    }
-  
-    return setResultMessage("Successfully backed up " + getSource() + " to " + getDestination() + ".");
-  }
-
-
-  /**
-   * Public interface to perform a backup into an output stream.
-   * This is callable directly, without an AST interface.
-   * @param conn The connection to a server to be backed up.
-   * @param source The URI describing the graph on the server to back up.
-   * @param outputStream The output which will receive the data to be backed up.
-   * @throws QueryException There was an error asking the server to perform the backup.
-   */
-  public static void backup(Connection conn, URI source, OutputStream outputStream) throws QueryException {
-    // open and wrap the outputstream
-    RemoteOutputStreamSrvImpl srv = new RemoteOutputStreamSrvImpl(outputStream);
-
-    // prepare it for exporting
-    try {
-      UnicastRemoteObject.exportObject(srv);
-    } catch (RemoteException rex) {
-      throw new QueryException("Unable to backup "+ source + " to an output stream", rex);
-    }
-
-    OutputStream marshallingOutputStream = new RemoteOutputStream(srv);
-
-    // perform the backup
-    try {
-      conn.getSession().backup(source, marshallingOutputStream);
-    } finally {
-      // cleanup the output
-      if (marshallingOutputStream != null) {
-        try {
-          marshallingOutputStream.close();
-        } catch (IOException ioe ) { /* ignore */ }
-      }
-      // cleanup the RMI for the output stream
-      if (srv != null) {
-        try {
-          UnicastRemoteObject.unexportObject(srv, false);
-        } catch (NoSuchObjectException ex) {};
-      }
-      try {
-        srv.close();
-      } catch (IOException e) {}
-    }
-  }
-
-
-  /**
-   * Perform the transfer with the configured datastream.
-   * @return The number of statements affected, or <code>null</code> if this is not relevant.
-   */
-  protected Long doTx(Connection conn, InputStream inputStream) throws QueryException {
-    return null;
-  }
-
-  /**
-   * Sets the server URI for this server operation.
-   * @param uri The URI to determine the server URI from.
-   */
-  private URI updateServerUri(URI uri) {
-    serverUri = calcServerUri(uri);
-    return serverUri;
-  }
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Backup.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Backup.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Backup.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Backup.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,160 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.rmi.NoSuchObjectException;
+import java.rmi.RemoteException;
+import java.rmi.server.UnicastRemoteObject;
+
+import org.apache.log4j.Logger;
+import org.mulgara.connection.Connection;
+import org.mulgara.query.QueryException;
+
+import edu.emory.mathcs.util.remote.io.RemoteOutputStream;
+import edu.emory.mathcs.util.remote.io.server.impl.RemoteOutputStreamSrvImpl;
+
+/**
+ * Represents a command to back data up from a model.
+ *
+ * @created Aug 19, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class Backup extends DataTx {
+  
+  private static final String FILE = "file";
+
+  /** The logger */
+  static final Logger logger = Logger.getLogger(Backup.class.getName());
+
+  /** The URI for the server. */
+  private URI serverUri;
+
+  /**
+   * Creates a new Backup command.
+   * @param source The data to back up.  May be a server or just a single graph.
+   * @param destination The location where to back the data up.
+   *        Only file URLs supported at the moment.
+   */
+  public Backup(URI source, URI destination, boolean locality) {
+    super(source, destination, source, locality);
+    if (!destination.getScheme().equals(FILE)) throw new IllegalArgumentException("Backups must be sent to a file");
+    updateServerUri(source);
+  }
+
+  /**
+   * @return The URI of the destination graph.
+   */
+  public URI getServerURI() throws UnsupportedOperationException {
+    return serverUri;
+  }
+
+
+  /**
+   * Perform a backup on a server.
+   * @param conn The connection to talk to the server on.
+   * @return The text describing the server that was backed up.
+   * @throws QueryException There was an error asking the server to perform the backup.
+   * @throws MalformedURLException The destination is not a valid file.
+   */
+  public Object execute(Connection conn) throws QueryException, MalformedURLException {
+    // test if the server can do all the work, or if data needs to be streamed
+    if (isLocal()) {
+      // server does all the work
+      conn.getSession().backup(getSource(), getDestination());
+    } else {
+      // need to stream data through to an output stream
+      FileOutputStream fileOutputStream = null;
+      String destinationFile = this.getDestination().toURL().getPath();
+      try {
+        fileOutputStream = new FileOutputStream(destinationFile);
+      } catch (FileNotFoundException ex) {
+        throw new QueryException("File " + destinationFile + " cannot be created for backup. ", ex);
+      }
+
+      // send to open method for backing up to a stream
+      backup(conn, getSource(), fileOutputStream);
+    }
+  
+    return setResultMessage("Successfully backed up " + getSource() + " to " + getDestination() + ".");
+  }
+
+
+  /**
+   * Public interface to perform a backup into an output stream.
+   * This is callable directly, without an AST interface.
+   * @param conn The connection to a server to be backed up.
+   * @param source The URI describing the graph on the server to back up.
+   * @param outputStream The output which will receive the data to be backed up.
+   * @throws QueryException There was an error asking the server to perform the backup.
+   */
+  public static void backup(Connection conn, URI source, OutputStream outputStream) throws QueryException {
+    // open and wrap the outputstream
+    RemoteOutputStreamSrvImpl srv = new RemoteOutputStreamSrvImpl(outputStream);
+
+    // prepare it for exporting
+    try {
+      UnicastRemoteObject.exportObject(srv);
+    } catch (RemoteException rex) {
+      throw new QueryException("Unable to backup "+ source + " to an output stream", rex);
+    }
+
+    OutputStream marshallingOutputStream = new RemoteOutputStream(srv);
+
+    // perform the backup
+    try {
+      conn.getSession().backup(source, marshallingOutputStream);
+    } finally {
+      // cleanup the output
+      if (marshallingOutputStream != null) {
+        try {
+          marshallingOutputStream.close();
+        } catch (IOException ioe ) { /* ignore */ }
+      }
+      // cleanup the RMI for the output stream
+      if (srv != null) {
+        try {
+          UnicastRemoteObject.unexportObject(srv, false);
+        } catch (NoSuchObjectException ex) {};
+      }
+      try {
+        srv.close();
+      } catch (IOException e) {}
+    }
+  }
+
+
+  /**
+   * Perform the transfer with the configured datastream.
+   * @return The number of statements affected, or <code>null</code> if this is not relevant.
+   */
+  protected Long doTx(Connection conn, InputStream inputStream) throws QueryException {
+    return null;
+  }
+
+  /**
+   * Sets the server URI for this server operation.
+   * @param uri The URI to determine the server URI from.
+   */
+  private URI updateServerUri(URI uri) {
+    serverUri = calcServerUri(uri);
+    return serverUri;
+  }
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,43 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-/**
- * This class indicates a command for the UI to set a local boolean property. 
- * @created Aug 17, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public abstract class BooleanSetCommand extends SetCommand {
-
-  protected static final String ON = "on";
-  protected static final String OFF = "off";
-
-  /** Indicates that option has been set on or off. */
-  private final boolean on;
-  
-  /**
-   * Create a command to set and option on or off.
-   * @param on <code>true</code> if the option is on.
-   */
-  public BooleanSetCommand(boolean on) {
-    this.on = on;
-  }
-  
-  /**
-   * @return the set option
-   */
-  public boolean isOn() {
-    return on;
-  }
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/BooleanSetCommand.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,43 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+/**
+ * This class indicates a command for the UI to set a local boolean property. 
+ * @created Aug 17, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public abstract class BooleanSetCommand extends SetCommand {
+
+  protected static final String ON = "on";
+  protected static final String OFF = "off";
+
+  /** Indicates that option has been set on or off. */
+  private final boolean on;
+  
+  /**
+   * Create a command to set and option on or off.
+   * @param on <code>true</code> if the option is on.
+   */
+  public BooleanSetCommand(boolean on) {
+    this.on = on;
+  }
+  
+  /**
+   * @return the set option
+   */
+  public boolean isOn() {
+    return on;
+  }
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Command.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Command.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Command.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,77 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-
-package org.mulgara.query.operation;
-
-import java.net.URI;
-
-import org.mulgara.connection.Connection;
-
-/**
- * A general Abstract Syntax Tree for TQL commands.
- *
- * @created 2007-08-09
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public interface Command {
-
-  /**
-   * Indicates that the command modifies the state in a transaction.
-   * @return <code>true</code> If the transaction state is to be modified.
-   */
-  boolean isTxCommitRollback();
-  
-  /**
-   * Indicates if an AST element is an operation for a local client.
-   * Local operations do not create a connection to a server, though they
-   * can modify the state of existing connections.
-   * @return <code>true</code> if the operation is only relevant to a client.
-   */
-  boolean isLocalOperation();
-  
-  /**
-   * Indicates if an AST represents a command for a user interface.
-   * @return <code>true</code> if the operation is only relevant to a user interface
-   */
-  boolean isUICommand();
-  
-  /**
-   * Gets the associated server for a non-local operation.
-   * @return the server URI if one can be determined,
-   *  or <code>null</code> if not a valid operation.
-   * @throws UnsupportedOperationException If this command is local only.
-   */
-  URI getServerURI() throws UnsupportedOperationException;
-
-  /**
-   * Executes the operation. This is highly specific to each operation.
-   * @return Data specific to the operation.
-   * @throws Exception specific to the operation.
-   */
-  Object execute(Connection conn) throws Exception;
-
-  /**
-   * Gets a message text relevant to the operation.  Useful for the UI.
-   * @return A text message associated with the result of this
-   * operation.
-   */
-  String getResultMessage();
-
-  /**
-   * Indicates that this command returns an Answer. Saves the overhead of checking
-   * the return type of execute.
-   * @return <code>true</code> if the result of execute is an Answer.
-   */
-  boolean isAnswerable();
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Command.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Command.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Command.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Command.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,77 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.query.operation;
+
+import java.net.URI;
+
+import org.mulgara.connection.Connection;
+
+/**
+ * A general Abstract Syntax Tree for TQL commands.
+ *
+ * @created 2007-08-09
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public interface Command {
+
+  /**
+   * Indicates that the command modifies the state in a transaction.
+   * @return <code>true</code> If the transaction state is to be modified.
+   */
+  boolean isTxCommitRollback();
+  
+  /**
+   * Indicates if an AST element is an operation for a local client.
+   * Local operations do not create a connection to a server, though they
+   * can modify the state of existing connections.
+   * @return <code>true</code> if the operation is only relevant to a client.
+   */
+  boolean isLocalOperation();
+  
+  /**
+   * Indicates if an AST represents a command for a user interface.
+   * @return <code>true</code> if the operation is only relevant to a user interface
+   */
+  boolean isUICommand();
+  
+  /**
+   * Gets the associated server for a non-local operation.
+   * @return the server URI if one can be determined,
+   *  or <code>null</code> if not a valid operation.
+   * @throws UnsupportedOperationException If this command is local only.
+   */
+  URI getServerURI() throws UnsupportedOperationException;
+
+  /**
+   * Executes the operation. This is highly specific to each operation.
+   * @return Data specific to the operation.
+   * @throws Exception specific to the operation.
+   */
+  Object execute(Connection conn) throws Exception;
+
+  /**
+   * Gets a message text relevant to the operation.  Useful for the UI.
+   * @return A text message associated with the result of this
+   * operation.
+   */
+  String getResultMessage();
+
+  /**
+   * Indicates that this command returns an Answer. Saves the overhead of checking
+   * the return type of execute.
+   * @return <code>true</code> if the result of execute is an Answer.
+   */
+  boolean isAnswerable();
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Commit.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Commit.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Commit.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,69 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-
-package org.mulgara.query.operation;
-
-
-import org.mulgara.connection.Connection;
-import org.mulgara.query.QueryException;
-import org.mulgara.server.Session;
-
-
-/**
- * An AST element for the COMMIT command. Not called directly for a TQL commit, as that
- * would have to go to all open connections. Consequently, TqlAutoInterpreter handles
- * commits through a different method to the standard call path, while the normal
- * call will pass in a {@link org.mulgara.connection.DummyConnection}.
- *
- * After performing a commit, all connections are left in place {@link #cleanup(Iterator)} and
- * the transaction is kept open {@link #stayInTx()}.
- * 
- * @created 2007-08-09
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class Commit extends TransactionCommand implements Command, TxOp {
-  
-  /**
-   * Commits the transaction on a connection.
-   * @param conn Contains the session to commit. 
-   * @throws QueryException There was a server error commiting the transaction.
-   */
-  public Object execute(Connection conn) throws QueryException {
-    Session session = conn.getSession();
-    if (session != null) {
-      session.commit();
-      return setResultMessage("Successfully committed transaction");
-    } else {
-      assert conn instanceof org.mulgara.connection.DummyConnection;
-      return setResultMessage("Skipped commit for internal connection");
-    }
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public boolean stayInTx() {
-    return true;
-  }
-
-
-  /**
-   * Sets message text relevant to the operation.  Exposes this publicly, but only for internal use.
-   * @return The set text.
-   */
-  public String setResultMessage(String resultMessage) {
-    return super.setResultMessage(resultMessage);
-  }
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Commit.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Commit.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Commit.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Commit.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,69 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.query.operation;
+
+
+import org.mulgara.connection.Connection;
+import org.mulgara.query.QueryException;
+import org.mulgara.server.Session;
+
+
+/**
+ * An AST element for the COMMIT command. Not called directly for a TQL commit, as that
+ * would have to go to all open connections. Consequently, TqlAutoInterpreter handles
+ * commits through a different method to the standard call path, while the normal
+ * call will pass in a {@link org.mulgara.connection.DummyConnection}.
+ *
+ * After performing a commit, all connections are left in place {@link #cleanup(Iterator)} and
+ * the transaction is kept open {@link #stayInTx()}.
+ * 
+ * @created 2007-08-09
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class Commit extends TransactionCommand implements Command, TxOp {
+  
+  /**
+   * Commits the transaction on a connection.
+   * @param conn Contains the session to commit. 
+   * @throws QueryException There was a server error commiting the transaction.
+   */
+  public Object execute(Connection conn) throws QueryException {
+    Session session = conn.getSession();
+    if (session != null) {
+      session.commit();
+      return setResultMessage("Successfully committed transaction");
+    } else {
+      assert conn instanceof org.mulgara.connection.DummyConnection;
+      return setResultMessage("Skipped commit for internal connection");
+    }
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public boolean stayInTx() {
+    return true;
+  }
+
+
+  /**
+   * Sets message text relevant to the operation.  Exposes this publicly, but only for internal use.
+   * @return The set text.
+   */
+  public String setResultMessage(String resultMessage) {
+    return super.setResultMessage(resultMessage);
+  }
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,70 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.net.URI;
-
-import org.apache.log4j.Logger;
-import org.mulgara.connection.Connection;
-
-/**
- * Represents a command to create a new graph.
- * @created Aug 10, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class CreateGraph extends ServerCommand {
-
-  /** The logger */
-  private static final Logger logger = Logger.getLogger(CreateGraph.class.getName());
-
-  /** The URI for the graph. */
-  private final URI graphUri;
-  
-  /** The URI for the type of the graph. */
-  private final URI type;
-  
-  public CreateGraph(URI graphUri, URI type) {
-    super(graphUri);
-    this.graphUri = graphUri;
-    this.type = type;
-  }
-  
-  /**
-   * Get the URI of the graph to create.
-   * @return the URI of the graph to create.
-   */
-  public URI getGraphUri() {
-    return graphUri;
-  }
-
-  /**
-   * Get the type of the graph to create.
-   * @return the type of the graph.
-   */
-  public URI getType() {
-    return type;
-  }
-
-  /**
-   * Perform the action of creating the graph.
-   * @param The connection to a session to create the graph in.
-   * @return Text describing the outcome.
-   */
-  public Object execute(Connection conn) throws Exception {
-    if (logger.isDebugEnabled()) logger.debug("Creating new model " + graphUri);
-    conn.getSession().createModel(graphUri, type);
-    return setResultMessage("Successfully created model " + graphUri);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/CreateGraph.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,70 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.net.URI;
+
+import org.apache.log4j.Logger;
+import org.mulgara.connection.Connection;
+
+/**
+ * Represents a command to create a new graph.
+ * @created Aug 10, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class CreateGraph extends ServerCommand {
+
+  /** The logger */
+  private static final Logger logger = Logger.getLogger(CreateGraph.class.getName());
+
+  /** The URI for the graph. */
+  private final URI graphUri;
+  
+  /** The URI for the type of the graph. */
+  private final URI type;
+  
+  public CreateGraph(URI graphUri, URI type) {
+    super(graphUri);
+    this.graphUri = graphUri;
+    this.type = type;
+  }
+  
+  /**
+   * Get the URI of the graph to create.
+   * @return the URI of the graph to create.
+   */
+  public URI getGraphUri() {
+    return graphUri;
+  }
+
+  /**
+   * Get the type of the graph to create.
+   * @return the type of the graph.
+   */
+  public URI getType() {
+    return type;
+  }
+
+  /**
+   * Perform the action of creating the graph.
+   * @param The connection to a session to create the graph in.
+   * @return Text describing the outcome.
+   */
+  public Object execute(Connection conn) throws Exception {
+    if (logger.isDebugEnabled()) logger.debug("Creating new model " + graphUri);
+    conn.getSession().createModel(graphUri, type);
+    return setResultMessage("Successfully created model " + graphUri);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DataTx.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/DataTx.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DataTx.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,213 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.rmi.NoSuchObjectException;
-import java.rmi.server.UnicastRemoteObject;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.ZipInputStream;
-
-import org.apache.log4j.Logger;
-import org.mulgara.connection.Connection;
-import org.mulgara.query.QueryException;
-
-import edu.emory.mathcs.util.remote.io.RemoteInputStream;
-import edu.emory.mathcs.util.remote.io.server.impl.RemoteInputStreamSrvImpl;
-
-/**
- * Represents a command to move data in or out of a model.
- *
- * @created Aug 13, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public abstract class DataTx extends ServerCommand {
-
-  /** The logger */
-  static final Logger logger = Logger.getLogger(DataTx.class.getName());
-
-  /** String constant for the extension of gzip files. */
-  private static final String GZIP_EXTENSION = ".gz";
-
-  /** String constant for the extension of zip files. */
-  private static final String ZIP_EXTENSION = ".zip";
-
-  /** The source of data to insert. */
-  private final URI source;
-  
-  /** The graph to load data into. */
-  private final URI destination;
-
-  /** Indicates that data is to be loaded locally from the client. */
-  private final boolean local;
-  
-  /** A stream to enable an API to load data directly. */
-  private InputStream overrideStream;
-
-  /**
-   * Create a new data transfer command for loads and restores.
-   * @param source The source of data to insert.
-   * @param destination The graph or server to load data into.
-   */
-  public DataTx(URI source, URI destination, URI serverGraphURI, boolean local) {
-    super(serverGraphURI);
-    // make sure that the URI given to the parent was a good one
-    assert source.equals(serverGraphURI) || destination.equals(serverGraphURI);
-    // test and store the parameters
-    if (source == null) throw new IllegalArgumentException("Need a valid source of data");
-    if (destination == null) throw new IllegalArgumentException("Need a valid destination for data");
-    this.source = source;
-    this.destination = destination;
-    this.local = local;
-    overrideStream = null;
-  }
-
-
-  /**
-   * Allows an API to set the stream for loading, instead of getting it from the
-   * source URI.
-   * @param overrideStream The stream to use for loading data.
-   */
-  public void setOverrideStream(InputStream overrideStream) {
-    this.overrideStream = overrideStream;
-  }
-
-  /**
-   * @return the URI of the source data.
-   */
-  public URI getSource() {
-    return source;
-  }
-
-  /**
-   * @return the destination URI for the data.
-   */
-  public URI getDestination() {
-    return destination;
-  }
-
-
-  /**
-   * @return the locality flag for the data.
-   */
-  public boolean isLocal() {
-    return local;
-  }
-
-
-  /**
-   * Perform the transfer with the configured datastream.
-   * @return The number of statements affected, or <code>null</code> if this is not relevant.
-   */
-  protected abstract Long doTx(Connection conn, InputStream inputStream) throws QueryException;
-
-
-  /**
-   * Wrap the file at the source URI in an RMI object for marshalling, and send over the connection.
-   * Used by Load and Restore, but not Backup, which marshalls in the opposite direction.
-   * @param conn The connection to the server.
-   * @return The number of statements inserted.
-   * @throws QueryException There was an error working with data at the server end.
-   * @throws IOException There was an error transferring data over the network.
-   */
-  protected long sendMarshalledData(Connection conn) throws QueryException, IOException {
-    if (logger.isInfoEnabled()) logger.info("loading local resource : " + source);
-
-    RemoteInputStreamSrvImpl srv = null;
-    RemoteInputStream remoteInputStream = null;
-    try {
-
-      // is the file/stream compressed?
-      InputStream inputStream = adjustForCompression(source.toURL());
-
-      // open and wrap the inputstream
-      srv = new RemoteInputStreamSrvImpl(inputStream);
-      UnicastRemoteObject.exportObject(srv);
-      remoteInputStream = new RemoteInputStream(srv);
-
-      // call back to the implementing class
-      return doTx(conn, remoteInputStream);
-
-    } finally {
-      // clean up the RMI object
-      if (srv != null) {
-        try {
-          UnicastRemoteObject.unexportObject(srv, false);
-        } catch (NoSuchObjectException ex) {};
-      }
-      try {
-        if (remoteInputStream != null) remoteInputStream.close();
-      } catch (Exception e) { }
-    }
-
-  }
-
-
-  /**
-   * Gets a stream for a file.  Determines if the stream is compressed by inspecting
-   * the fileName extension.
-   *
-   * @return a new stream which supplies uncompressed data from the file location. 
-   * @param fileLocation String The URL for the file being loaded
-   * @throws IOException An error while reading from the input stream.
-   * @return InputStream A new input stream which supplies uncompressed data.
-   */
-  private InputStream adjustForCompression(URL fileLocation) throws IOException {
-
-    if (fileLocation == null) throw new IllegalArgumentException("File name is null");
-
-    InputStream stream = (overrideStream == null) ? fileLocation.openStream() : overrideStream;
-
-    // wrap the stream in a decompressor if the suffixes indicate this should happen.
-    String fileName = fileLocation.toString();
-    if (fileName.toLowerCase().endsWith(GZIP_EXTENSION)) {
-      stream = new GZIPInputStream(stream);
-    } else if (fileName.toLowerCase().endsWith(ZIP_EXTENSION)) {
-      stream = new ZipInputStream(stream);
-    }
-
-    assert stream != null;
-    return stream;
-  }
-  
-
-  /**
-   * Determine the URI to be used for a server when processing a backup.
-   * @param uri Can contain the URI of a graph, or of an entire server.
-   * @return The URI for the server containing the uri.
-   */
-  public static URI calcServerUri(URI uri) {
-    URI calcUri = null;
-    
-    // check if backing up a graph or a server
-    String fragment = uri.getFragment();
-    if (fragment == null) {
-      if (logger.isDebugEnabled()) logger.debug("Backup for server: " + uri);
-      calcUri = uri;
-    } else {
-      String serverUriString = uri.toString().replaceAll("#" + fragment, "");
-      try {
-        calcUri = new URI(serverUriString);
-      } catch (URISyntaxException e) {
-        throw new Error("Unable to truncate a fragment from a valid URI");
-      }
-    }
-    return calcUri;
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DataTx.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/DataTx.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DataTx.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DataTx.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,213 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.rmi.NoSuchObjectException;
+import java.rmi.server.UnicastRemoteObject;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.ZipInputStream;
+
+import org.apache.log4j.Logger;
+import org.mulgara.connection.Connection;
+import org.mulgara.query.QueryException;
+
+import edu.emory.mathcs.util.remote.io.RemoteInputStream;
+import edu.emory.mathcs.util.remote.io.server.impl.RemoteInputStreamSrvImpl;
+
+/**
+ * Represents a command to move data in or out of a model.
+ *
+ * @created Aug 13, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public abstract class DataTx extends ServerCommand {
+
+  /** The logger */
+  static final Logger logger = Logger.getLogger(DataTx.class.getName());
+
+  /** String constant for the extension of gzip files. */
+  private static final String GZIP_EXTENSION = ".gz";
+
+  /** String constant for the extension of zip files. */
+  private static final String ZIP_EXTENSION = ".zip";
+
+  /** The source of data to insert. */
+  private final URI source;
+  
+  /** The graph to load data into. */
+  private final URI destination;
+
+  /** Indicates that data is to be loaded locally from the client. */
+  private final boolean local;
+  
+  /** A stream to enable an API to load data directly. */
+  private InputStream overrideStream;
+
+  /**
+   * Create a new data transfer command for loads and restores.
+   * @param source The source of data to insert.
+   * @param destination The graph or server to load data into.
+   */
+  public DataTx(URI source, URI destination, URI serverGraphURI, boolean local) {
+    super(serverGraphURI);
+    // make sure that the URI given to the parent was a good one
+    assert source.equals(serverGraphURI) || destination.equals(serverGraphURI);
+    // test and store the parameters
+    if (source == null) throw new IllegalArgumentException("Need a valid source of data");
+    if (destination == null) throw new IllegalArgumentException("Need a valid destination for data");
+    this.source = source;
+    this.destination = destination;
+    this.local = local;
+    overrideStream = null;
+  }
+
+
+  /**
+   * Allows an API to set the stream for loading, instead of getting it from the
+   * source URI.
+   * @param overrideStream The stream to use for loading data.
+   */
+  public void setOverrideStream(InputStream overrideStream) {
+    this.overrideStream = overrideStream;
+  }
+
+  /**
+   * @return the URI of the source data.
+   */
+  public URI getSource() {
+    return source;
+  }
+
+  /**
+   * @return the destination URI for the data.
+   */
+  public URI getDestination() {
+    return destination;
+  }
+
+
+  /**
+   * @return the locality flag for the data.
+   */
+  public boolean isLocal() {
+    return local;
+  }
+
+
+  /**
+   * Perform the transfer with the configured datastream.
+   * @return The number of statements affected, or <code>null</code> if this is not relevant.
+   */
+  protected abstract Long doTx(Connection conn, InputStream inputStream) throws QueryException;
+
+
+  /**
+   * Wrap the file at the source URI in an RMI object for marshalling, and send over the connection.
+   * Used by Load and Restore, but not Backup, which marshalls in the opposite direction.
+   * @param conn The connection to the server.
+   * @return The number of statements inserted.
+   * @throws QueryException There was an error working with data at the server end.
+   * @throws IOException There was an error transferring data over the network.
+   */
+  protected long sendMarshalledData(Connection conn) throws QueryException, IOException {
+    if (logger.isInfoEnabled()) logger.info("loading local resource : " + source);
+
+    RemoteInputStreamSrvImpl srv = null;
+    RemoteInputStream remoteInputStream = null;
+    try {
+
+      // is the file/stream compressed?
+      InputStream inputStream = adjustForCompression(source.toURL());
+
+      // open and wrap the inputstream
+      srv = new RemoteInputStreamSrvImpl(inputStream);
+      UnicastRemoteObject.exportObject(srv);
+      remoteInputStream = new RemoteInputStream(srv);
+
+      // call back to the implementing class
+      return doTx(conn, remoteInputStream);
+
+    } finally {
+      // clean up the RMI object
+      if (srv != null) {
+        try {
+          UnicastRemoteObject.unexportObject(srv, false);
+        } catch (NoSuchObjectException ex) {};
+      }
+      try {
+        if (remoteInputStream != null) remoteInputStream.close();
+      } catch (Exception e) { }
+    }
+
+  }
+
+
+  /**
+   * Gets a stream for a file.  Determines if the stream is compressed by inspecting
+   * the fileName extension.
+   *
+   * @return a new stream which supplies uncompressed data from the file location. 
+   * @param fileLocation String The URL for the file being loaded
+   * @throws IOException An error while reading from the input stream.
+   * @return InputStream A new input stream which supplies uncompressed data.
+   */
+  private InputStream adjustForCompression(URL fileLocation) throws IOException {
+
+    if (fileLocation == null) throw new IllegalArgumentException("File name is null");
+
+    InputStream stream = (overrideStream == null) ? fileLocation.openStream() : overrideStream;
+
+    // wrap the stream in a decompressor if the suffixes indicate this should happen.
+    String fileName = fileLocation.toString();
+    if (fileName.toLowerCase().endsWith(GZIP_EXTENSION)) {
+      stream = new GZIPInputStream(stream);
+    } else if (fileName.toLowerCase().endsWith(ZIP_EXTENSION)) {
+      stream = new ZipInputStream(stream);
+    }
+
+    assert stream != null;
+    return stream;
+  }
+  
+
+  /**
+   * Determine the URI to be used for a server when processing a backup.
+   * @param uri Can contain the URI of a graph, or of an entire server.
+   * @return The URI for the server containing the uri.
+   */
+  public static URI calcServerUri(URI uri) {
+    URI calcUri = null;
+    
+    // check if backing up a graph or a server
+    String fragment = uri.getFragment();
+    if (fragment == null) {
+      if (logger.isDebugEnabled()) logger.debug("Backup for server: " + uri);
+      calcUri = uri;
+    } else {
+      String serverUriString = uri.toString().replaceAll("#" + fragment, "");
+      try {
+        calcUri = new URI(serverUriString);
+      } catch (URISyntaxException e) {
+        throw new Error("Unable to truncate a fragment from a valid URI");
+      }
+    }
+    return calcUri;
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Deletion.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Deletion.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Deletion.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,59 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.net.URI;
-import java.util.Set;
-
-import org.jrdf.graph.Triple;
-import org.mulgara.connection.Connection;
-import org.mulgara.query.Query;
-
-/**
- * An AST element for deleting from a graph.
- * @created Aug 15, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class Deletion extends Modification {
-  
-  /**
-   * Create a deletion command for deleting a set of statements from a graph.
-   * @param graph The graph to delete from.
-   * @param statements The data to be deleted.
-   */
-  public Deletion(URI graph, Set<Triple> statements){
-    super(graph, statements);
-  }
-
-  /**
-   * Create an deletion command for deleting the results of a query from a graph.
-   * @param graph The graph to delete from.
-   * @param selectQuery The query to get data from for deletion.
-   */
-  public Deletion(URI graph, Query selectQuery){
-    super(graph, selectQuery);
-  }
-
-  /**
-   * Performs the deletion.
-   * @param conn the session to delete the data from the graph in.
-   * @return Text describing the action.
-   */
-  public Object execute(Connection conn) throws Exception {
-    if (isSelectBased()) conn.getSession().delete(graph, getSelectQuery());
-    else conn.getSession().delete(graph, getStatements());
-    return setResultMessage("Successfully deleted statements from " + graph);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Deletion.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Deletion.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Deletion.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Deletion.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,59 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.net.URI;
+import java.util.Set;
+
+import org.jrdf.graph.Triple;
+import org.mulgara.connection.Connection;
+import org.mulgara.query.Query;
+
+/**
+ * An AST element for deleting from a graph.
+ * @created Aug 15, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class Deletion extends Modification {
+  
+  /**
+   * Create a deletion command for deleting a set of statements from a graph.
+   * @param graph The graph to delete from.
+   * @param statements The data to be deleted.
+   */
+  public Deletion(URI graph, Set<Triple> statements){
+    super(graph, statements);
+  }
+
+  /**
+   * Create an deletion command for deleting the results of a query from a graph.
+   * @param graph The graph to delete from.
+   * @param selectQuery The query to get data from for deletion.
+   */
+  public Deletion(URI graph, Query selectQuery){
+    super(graph, selectQuery);
+  }
+
+  /**
+   * Performs the deletion.
+   * @param conn the session to delete the data from the graph in.
+   * @return Text describing the action.
+   */
+  public Object execute(Connection conn) throws Exception {
+    if (isSelectBased()) conn.getSession().delete(graph, getSelectQuery());
+    else conn.getSession().delete(graph, getStatements());
+    return setResultMessage("Successfully deleted statements from " + graph);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DropGraph.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/DropGraph.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DropGraph.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,53 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.net.URI;
-
-import org.mulgara.connection.Connection;
-
-/**
- * Represents a command to drop a graph.
- * @created Aug 10, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class DropGraph extends ServerCommand {
-
-  /** The URI for the graph. */
-  private final URI graphUri;
-  
-  public DropGraph(URI graphUri) {
-    super(graphUri);
-    this.graphUri = graphUri;
-  }
-  
-  /**
-   * Get the URI of the graph to drop.
-   * @return the URI of the graph to drop.
-   */
-  public URI getGraphUri() {
-    return graphUri;
-  }
-
-  /**
-   * Performs the deletion.
-   * @param conn the session to delete the graph in.
-   * @return Text describing the action.
-   */
-  public Object execute(Connection conn) throws Exception {
-    conn.getSession().removeModel(graphUri);
-    return setResultMessage("Successfully dropped model " + graphUri);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DropGraph.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/DropGraph.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DropGraph.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/DropGraph.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,53 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.net.URI;
+
+import org.mulgara.connection.Connection;
+
+/**
+ * Represents a command to drop a graph.
+ * @created Aug 10, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class DropGraph extends ServerCommand {
+
+  /** The URI for the graph. */
+  private final URI graphUri;
+  
+  public DropGraph(URI graphUri) {
+    super(graphUri);
+    this.graphUri = graphUri;
+  }
+  
+  /**
+   * Get the URI of the graph to drop.
+   * @return the URI of the graph to drop.
+   */
+  public URI getGraphUri() {
+    return graphUri;
+  }
+
+  /**
+   * Performs the deletion.
+   * @param conn the session to delete the graph in.
+   * @return Text describing the action.
+   */
+  public Object execute(Connection conn) throws Exception {
+    conn.getSession().removeModel(graphUri);
+    return setResultMessage("Successfully dropped model " + graphUri);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,105 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.net.URL;
-
-import org.apache.log4j.Logger;
-import org.mulgara.connection.Connection;
-import org.mulgara.parser.MulgaraLexerException;
-import org.mulgara.parser.Interpreter;
-import org.mulgara.parser.MulgaraParserException;
-
-/**
- * An AST element for running an external script.
- * @created Aug 14, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class ExecuteScript extends LocalCommand {
-
-  /** The logger */
-  static final Logger logger = Logger.getLogger(ExecuteScript.class.getName());
-
-  /** The script to be executed. */
-  private final URL script;
-  
-  /** The interpreter for the script. */
-  final Interpreter interpreter;
-  
-  
-  /**
-   * Creates a script execution command.
-   * @param script The script to execute.
-   */
-  public ExecuteScript(URL script, Interpreter interpreter) {
-    this.script = script;
-    this.interpreter = interpreter;
-  }
-
-  /**
-   * Indicates that this is a command for the UI.
-   * @return <code>true</code> to indicated that script execution is a UI feature.
-   */
-  public boolean isUICommand() {
-    return true;
-  }
-
-  /**
-   * @return the script URL
-   */
-  public URL getScript() {
-    return script;
-  }
-
-  /**
-   * Perform a series of actions, read from a file.
-   * @param conn The connection to perform the actions on.  Only one connection can be used.
-   * @return A string containing the accumulation of output messages from all commands in the
-   *         script, separated by newlines.
-   */
-  public Object execute(Connection conn) throws Exception {
-    // create a buffer to hold the results in
-    StringBuffer resultsMsg = new StringBuffer();
-
-    // create a reader to read the contents of the script
-    BufferedReader scriptIn = new BufferedReader(new InputStreamReader(script.openStream()));
-
-    // execute the script!
-    int line = 0;
-    try {
-      String commandLine;
-      while (null != (commandLine = scriptIn.readLine())) {
-        line++;
-        if (!commandLine.equals("")) {
-          Command cmd = interpreter.parseCommand(commandLine);
-          cmd.execute(conn);
-          resultsMsg.append(cmd.getResultMessage()).append("\n");
-        }
-      }
-      resultsMsg.append("Completed execution of script " + script);
-      setResultMessage(resultsMsg.toString());
-    } catch (MulgaraParserException pe) {
-      setResultMessage("Syntax error in script (line " + line + "): " + pe.getMessage());
-      logger.warn("Unable to execute script - " + script + "\n" + pe.getMessage());
-    } catch (MulgaraLexerException le) {
-      setResultMessage("Syntax error in script (line " + line + "): " + le.getMessage());
-      logger.warn("Unable to execute script - " + script + "\n" + le.getMessage());
-    }
-
-    return getResultMessage();
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/ExecuteScript.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,105 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.net.URL;
+
+import org.apache.log4j.Logger;
+import org.mulgara.connection.Connection;
+import org.mulgara.parser.MulgaraLexerException;
+import org.mulgara.parser.Interpreter;
+import org.mulgara.parser.MulgaraParserException;
+
+/**
+ * An AST element for running an external script.
+ * @created Aug 14, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class ExecuteScript extends LocalCommand {
+
+  /** The logger */
+  static final Logger logger = Logger.getLogger(ExecuteScript.class.getName());
+
+  /** The script to be executed. */
+  private final URL script;
+  
+  /** The interpreter for the script. */
+  final Interpreter interpreter;
+  
+  
+  /**
+   * Creates a script execution command.
+   * @param script The script to execute.
+   */
+  public ExecuteScript(URL script, Interpreter interpreter) {
+    this.script = script;
+    this.interpreter = interpreter;
+  }
+
+  /**
+   * Indicates that this is a command for the UI.
+   * @return <code>true</code> to indicated that script execution is a UI feature.
+   */
+  public boolean isUICommand() {
+    return true;
+  }
+
+  /**
+   * @return the script URL
+   */
+  public URL getScript() {
+    return script;
+  }
+
+  /**
+   * Perform a series of actions, read from a file.
+   * @param conn The connection to perform the actions on.  Only one connection can be used.
+   * @return A string containing the accumulation of output messages from all commands in the
+   *         script, separated by newlines.
+   */
+  public Object execute(Connection conn) throws Exception {
+    // create a buffer to hold the results in
+    StringBuffer resultsMsg = new StringBuffer();
+
+    // create a reader to read the contents of the script
+    BufferedReader scriptIn = new BufferedReader(new InputStreamReader(script.openStream()));
+
+    // execute the script!
+    int line = 0;
+    try {
+      String commandLine;
+      while (null != (commandLine = scriptIn.readLine())) {
+        line++;
+        if (!commandLine.equals("")) {
+          Command cmd = interpreter.parseCommand(commandLine);
+          cmd.execute(conn);
+          resultsMsg.append(cmd.getResultMessage()).append("\n");
+        }
+      }
+      resultsMsg.append("Completed execution of script " + script);
+      setResultMessage(resultsMsg.toString());
+    } catch (MulgaraParserException pe) {
+      setResultMessage("Syntax error in script (line " + line + "): " + pe.getMessage());
+      logger.warn("Unable to execute script - " + script + "\n" + pe.getMessage());
+    } catch (MulgaraLexerException le) {
+      setResultMessage("Syntax error in script (line " + line + "): " + le.getMessage());
+      logger.warn("Unable to execute script - " + script + "\n" + le.getMessage());
+    }
+
+    return getResultMessage();
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Help.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Help.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Help.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,60 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-
-package org.mulgara.query.operation;
-
-import org.mulgara.connection.Connection;
-
-
-/**
- * An AST element for the HELP command.
- *
- * @created 2007-08-09
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class Help extends LocalCommand {
-
-  private final String helpText;
-  
-  public Help(String helpText) {
-    this.helpText = helpText;
-  }
-  
-  /**
-   * Indicates that this operation is for a UI.
-   * @return <code>true</code> as operation is for UI output only.
-   */
-  public boolean isUICommand() {
-    return true;
-  }
-
-  /**
-   * Get the text that was requested from this object.
-   * @return The help text requested.
-   */
-  public String getOutput() {
-    // let the user know the help for the selected command
-    return helpText;
-  }
-
-  /**
-   * Asks for the help text associated with the creation of this object.
-   * @param conn ignored.
-   * @return The text of the help request.
-   */
-  public Object execute(Connection conn) throws Exception {
-    return setResultMessage(helpText);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Help.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Help.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Help.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Help.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,60 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.query.operation;
+
+import org.mulgara.connection.Connection;
+
+
+/**
+ * An AST element for the HELP command.
+ *
+ * @created 2007-08-09
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class Help extends LocalCommand {
+
+  private final String helpText;
+  
+  public Help(String helpText) {
+    this.helpText = helpText;
+  }
+  
+  /**
+   * Indicates that this operation is for a UI.
+   * @return <code>true</code> as operation is for UI output only.
+   */
+  public boolean isUICommand() {
+    return true;
+  }
+
+  /**
+   * Get the text that was requested from this object.
+   * @return The help text requested.
+   */
+  public String getOutput() {
+    // let the user know the help for the selected command
+    return helpText;
+  }
+
+  /**
+   * Asks for the help text associated with the creation of this object.
+   * @param conn ignored.
+   * @return The text of the help request.
+   */
+  public Object execute(Connection conn) throws Exception {
+    return setResultMessage(helpText);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Insertion.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Insertion.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Insertion.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,69 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.net.URI;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.jrdf.graph.Triple;
-import org.mulgara.connection.Connection;
-import org.mulgara.query.Query;
-
-/**
- * An AST element for inserting into a graph.
- * @created Aug 14, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class Insertion extends Modification {
-  
-  /**
-   * A redundant constructor to handle some broken reflection code.
-   * @param graph The graph to insert into.
-   * @param statements The data to be inserted.
-   */
-  public Insertion(URI graph, HashSet<Triple> statements) {
-    super(graph, (Set<Triple>)statements);
-  }
-
-  /**
-   * Create an insertion command for inserting a set of statements into a graph.
-   * @param graph The graph to insert into.
-   * @param statements The data to be inserted.
-   */
-  public Insertion(URI graph, Set<Triple> statements) {
-    super(graph, statements);
-  }
-
-  /**
-   * Create an insertion command for inserting the results of a query into a graph.
-   * @param graph The graph to insert into.
-   * @param selectQuery The query to get data from for insertion.
-   */
-  public Insertion(URI graph, Query selectQuery) {
-    super(graph, selectQuery);
-  }
-
-  /**
-   * Performs the insertion.
-   * @param conn the session for the graph to insert the data into.
-   * @return Text describing the action.
-   */
-  public Object execute(Connection conn) throws Exception {
-    if (isSelectBased()) conn.getSession().insert(graph, getSelectQuery());
-    else conn.getSession().insert(graph, getStatements());
-    return setResultMessage("Successfully inserted statements into " + graph);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Insertion.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Insertion.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Insertion.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Insertion.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,69 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.net.URI;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.jrdf.graph.Triple;
+import org.mulgara.connection.Connection;
+import org.mulgara.query.Query;
+
+/**
+ * An AST element for inserting into a graph.
+ * @created Aug 14, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class Insertion extends Modification {
+  
+  /**
+   * A redundant constructor to handle some broken reflection code.
+   * @param graph The graph to insert into.
+   * @param statements The data to be inserted.
+   */
+  public Insertion(URI graph, HashSet<Triple> statements) {
+    super(graph, (Set<Triple>)statements);
+  }
+
+  /**
+   * Create an insertion command for inserting a set of statements into a graph.
+   * @param graph The graph to insert into.
+   * @param statements The data to be inserted.
+   */
+  public Insertion(URI graph, Set<Triple> statements) {
+    super(graph, statements);
+  }
+
+  /**
+   * Create an insertion command for inserting the results of a query into a graph.
+   * @param graph The graph to insert into.
+   * @param selectQuery The query to get data from for insertion.
+   */
+  public Insertion(URI graph, Query selectQuery) {
+    super(graph, selectQuery);
+  }
+
+  /**
+   * Performs the insertion.
+   * @param conn the session for the graph to insert the data into.
+   * @return Text describing the action.
+   */
+  public Object execute(Connection conn) throws Exception {
+    if (isSelectBased()) conn.getSession().insert(graph, getSelectQuery());
+    else conn.getSession().insert(graph, getStatements());
+    return setResultMessage("Successfully inserted statements into " + graph);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Load.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Load.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Load.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,83 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-
-import org.apache.log4j.Logger;
-import org.mulgara.connection.Connection;
-import org.mulgara.query.ModelResource;
-import org.mulgara.query.QueryException;
-
-/**
- * Represents a command to load data into a model.
- *
- * @created Aug 19, 2007
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class Load extends DataTx {
-
-  /** The logger */
-  static final Logger logger = Logger.getLogger(Load.class.getName());
-  
-  /** Model resource form of the source URI */
-  private final ModelResource srcRsc;
-
-  /**
-   * Build a load operation, loading data from one URI into a graph specified by another URI.
-   * @param source The URI of the source of the RDF data.
-   * @param destination The URI of the graph to receive the data.
-   * @param local Set to <code>true</code> to indicate that the source is on the client system.
-   */
-  public Load(URI source, URI destination, boolean local) {
-    super(source, destination, destination, local);
-    srcRsc = new ModelResource(source);
-  }
-
-
-  /**
-   * Load the data into the destination graph through the given connection.
-   * @param conn The connection to load the data over.
-   * @return The number of statements that were inserted.
-   */
-  public Object execute(Connection conn) throws Exception {
-    URI src = getSource();
-    URI dest = getDestination();
-    try {
-      long stmtCount = isLocal() ? sendMarshalledData(conn) : conn.getSession().setModel(dest, srcRsc);
-      if (logger.isDebugEnabled()) logger.debug("Loaded " + stmtCount + " statements from " + src + " into " + dest);
-  
-      if (stmtCount > 0L) setResultMessage("Successfully loaded " + stmtCount + " statements from " + src + " into " + dest);
-      else setResultMessage("WARNING: No valid RDF statements found in " + src);
-      
-      return stmtCount;
-      
-    } catch (IOException ex) {
-      logger.error("Error attempting to load : " + src, ex);
-      throw new QueryException("Error attempting to load : " + src, ex);
-    }
-  }
-
-
-  /**
-   * Perform the transfer with the configured datastream.
-   * @return The number of statements affected, or <code>null</code> if this is not relevant.
-   */
-  protected Long doTx(Connection conn, InputStream inputStream) throws QueryException {
-    return conn.getSession().setModel(inputStream, getDestination(), srcRsc);
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Load.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Load.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Load.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Load.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,83 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+
+import org.apache.log4j.Logger;
+import org.mulgara.connection.Connection;
+import org.mulgara.query.ModelResource;
+import org.mulgara.query.QueryException;
+
+/**
+ * Represents a command to load data into a model.
+ *
+ * @created Aug 19, 2007
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class Load extends DataTx {
+
+  /** The logger */
+  static final Logger logger = Logger.getLogger(Load.class.getName());
+  
+  /** Model resource form of the source URI */
+  private final ModelResource srcRsc;
+
+  /**
+   * Build a load operation, loading data from one URI into a graph specified by another URI.
+   * @param source The URI of the source of the RDF data.
+   * @param destination The URI of the graph to receive the data.
+   * @param local Set to <code>true</code> to indicate that the source is on the client system.
+   */
+  public Load(URI source, URI destination, boolean local) {
+    super(source, destination, destination, local);
+    srcRsc = new ModelResource(source);
+  }
+
+
+  /**
+   * Load the data into the destination graph through the given connection.
+   * @param conn The connection to load the data over.
+   * @return The number of statements that were inserted.
+   */
+  public Object execute(Connection conn) throws Exception {
+    URI src = getSource();
+    URI dest = getDestination();
+    try {
+      long stmtCount = isLocal() ? sendMarshalledData(conn) : conn.getSession().setModel(dest, srcRsc);
+      if (logger.isDebugEnabled()) logger.debug("Loaded " + stmtCount + " statements from " + src + " into " + dest);
+  
+      if (stmtCount > 0L) setResultMessage("Successfully loaded " + stmtCount + " statements from " + src + " into " + dest);
+      else setResultMessage("WARNING: No valid RDF statements found in " + src);
+      
+      return stmtCount;
+      
+    } catch (IOException ex) {
+      logger.error("Error attempting to load : " + src, ex);
+      throw new QueryException("Error attempting to load : " + src, ex);
+    }
+  }
+
+
+  /**
+   * Perform the transfer with the configured datastream.
+   * @return The number of statements affected, or <code>null</code> if this is not relevant.
+   */
+  protected Long doTx(Connection conn, InputStream inputStream) throws QueryException {
+    return conn.getSession().setModel(inputStream, getDestination(), srcRsc);
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,97 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-
-package org.mulgara.query.operation;
-
-import java.net.URI;
-
-/**
- * An AST element for non-server commands.
- *
- * @created 2007-08-09
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public abstract class LocalCommand implements Command {
-
-  /** The message set by the result of this command. */
-  private String resultMessage = "";
-
-  /**
-   * Indicates that the command modifies the state in a transaction.
-   * @return <code>true</code> If the transaction state is to be modified.
-   */
-  public boolean isTxCommitRollback() {
-    return false;
-  }
-  
-  /**
-   * Indicates that this operation is local.
-   * @return Always <code>true</code> to indicate this command is local.
-   */
-  public final boolean isLocalOperation() {
-    return true;
-  }
-
-  /**
-   * Queries if this command is a request to quit.
-   * @return <code>false</code> for most operations, but <code>true</code> if quitting.
-   */
-  public boolean isQuitCommand() {
-    return false;
-  }
-
-
-  /**
-   * Indicates that this command cannot return an Answer.
-   * @return <code>false</code> by default.
-   */
-  public boolean isAnswerable() {
-    return false;
-  }
-
-
-  /**
-   * Gets the associated server for a non-local operation.
-   * @throws UnsupportedOperationException Always thrown for local commands.
-   */
-  public URI getServerURI() throws UnsupportedOperationException {
-    return null;
-  }
-  
-  /**
-   * Executes the operation. This is highly specific to each operation.
-   * @return Data specific to the operation.
-   * @throws Exception specific to the operation.
-   */
-  public Object execute() throws Exception {
-    return execute(null);
-  }
-  
-  /**
-   * Gets a message text relevant to the operation.  Useful for the UI.
-   * @return A text message associated with the result of this
-   * operation.
-   */
-  public String getResultMessage() {
-    return resultMessage;
-  }
-
-  /**
-   * Sets message text relevant to the operation.  Useful for the UI.
-   * @return The set text.
-   */
-  String setResultMessage(String resultMessage) {
-    return this.resultMessage = resultMessage;
-  }
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/LocalCommand.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,97 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.query.operation;
+
+import java.net.URI;
+
+/**
+ * An AST element for non-server commands.
+ *
+ * @created 2007-08-09
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public abstract class LocalCommand implements Command {
+
+  /** The message set by the result of this command. */
+  private String resultMessage = "";
+
+  /**
+   * Indicates that the command modifies the state in a transaction.
+   * @return <code>true</code> If the transaction state is to be modified.
+   */
+  public boolean isTxCommitRollback() {
+    return false;
+  }
+  
+  /**
+   * Indicates that this operation is local.
+   * @return Always <code>true</code> to indicate this command is local.
+   */
+  public final boolean isLocalOperation() {
+    return true;
+  }
+
+  /**
+   * Queries if this command is a request to quit.
+   * @return <code>false</code> for most operations, but <code>true</code> if quitting.
+   */
+  public boolean isQuitCommand() {
+    return false;
+  }
+
+
+  /**
+   * Indicates that this command cannot return an Answer.
+   * @return <code>false</code> by default.
+   */
+  public boolean isAnswerable() {
+    return false;
+  }
+
+
+  /**
+   * Gets the associated server for a non-local operation.
+   * @throws UnsupportedOperationException Always thrown for local commands.
+   */
+  public URI getServerURI() throws UnsupportedOperationException {
+    return null;
+  }
+  
+  /**
+   * Executes the operation. This is highly specific to each operation.
+   * @return Data specific to the operation.
+   * @throws Exception specific to the operation.
+   */
+  public Object execute() throws Exception {
+    return execute(null);
+  }
+  
+  /**
+   * Gets a message text relevant to the operation.  Useful for the UI.
+   * @return A text message associated with the result of this
+   * operation.
+   */
+  public String getResultMessage() {
+    return resultMessage;
+  }
+
+  /**
+   * Sets message text relevant to the operation.  Useful for the UI.
+   * @return The set text.
+   */
+  String setResultMessage(String resultMessage) {
+    return this.resultMessage = resultMessage;
+  }
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Modification.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Modification.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Modification.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,85 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-
-package org.mulgara.query.operation;
-
-import java.net.URI;
-import java.util.Set;
-
-import org.jrdf.graph.Triple;
-import org.mulgara.query.Query;
-
-public abstract class Modification extends ServerCommand {
-
-  /** The graph to insert into. */
-  protected final URI graph;
-  /** A SELECT query where the results are to be inserted into the graph. */
-  protected final Query selectQuery;
-  /** A set of statements to be inserted into the graph. */
-  protected final Set<Triple> statements;
-
-  /**
-   * Create a modification command for modifying a set of statements in a graph.
-   * @param graph The graph to modify.
-   * @param statements The data to be modified.
-   */
-  public Modification(URI graph, Set<Triple> statements){
-    super(graph);
-    this.graph = graph;
-    this.statements = statements;
-    this.selectQuery = null;
-  }
-
-  /**
-   * Create a modification command for modifying the results of a query in a graph.
-   * @param graph The graph to modify.
-   * @param selectQuery The query to get data for modification.
-   */
-  public Modification(URI graph, Query selectQuery){
-    super(graph);
-    this.graph = graph;
-    this.selectQuery = selectQuery;
-    this.statements = null;
-  }
-
-  /**
-   * Test is this insertion is based on a SELECT query.
-   * @return <code>true</code> if the data to be inserted comes from a SELECT query.
-   *         <code>false</code> otherwise.
-   */
-  public boolean isSelectBased() {
-    assert selectQuery == null ^ statements == null;
-    return selectQuery != null;
-  }
-
-  /**
-   * @return the graph
-   */
-  public URI getGraph() {
-    return graph;
-  }
-
-  /**
-   * @return the selectQuery
-   */
-  public Query getSelectQuery() {
-    return selectQuery;
-  }
-
-  /**
-   * @return the statements
-   */
-  public Set<Triple> getStatements() {
-    return statements;
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Modification.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Modification.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Modification.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Modification.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,85 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.query.operation;
+
+import java.net.URI;
+import java.util.Set;
+
+import org.jrdf.graph.Triple;
+import org.mulgara.query.Query;
+
+public abstract class Modification extends ServerCommand {
+
+  /** The graph to insert into. */
+  protected final URI graph;
+  /** A SELECT query where the results are to be inserted into the graph. */
+  protected final Query selectQuery;
+  /** A set of statements to be inserted into the graph. */
+  protected final Set<Triple> statements;
+
+  /**
+   * Create a modification command for modifying a set of statements in a graph.
+   * @param graph The graph to modify.
+   * @param statements The data to be modified.
+   */
+  public Modification(URI graph, Set<Triple> statements){
+    super(graph);
+    this.graph = graph;
+    this.statements = statements;
+    this.selectQuery = null;
+  }
+
+  /**
+   * Create a modification command for modifying the results of a query in a graph.
+   * @param graph The graph to modify.
+   * @param selectQuery The query to get data for modification.
+   */
+  public Modification(URI graph, Query selectQuery){
+    super(graph);
+    this.graph = graph;
+    this.selectQuery = selectQuery;
+    this.statements = null;
+  }
+
+  /**
+   * Test is this insertion is based on a SELECT query.
+   * @return <code>true</code> if the data to be inserted comes from a SELECT query.
+   *         <code>false</code> otherwise.
+   */
+  public boolean isSelectBased() {
+    assert selectQuery == null ^ statements == null;
+    return selectQuery != null;
+  }
+
+  /**
+   * @return the graph
+   */
+  public URI getGraph() {
+    return graph;
+  }
+
+  /**
+   * @return the selectQuery
+   */
+  public Query getSelectQuery() {
+    return selectQuery;
+  }
+
+  /**
+   * @return the statements
+   */
+  public Set<Triple> getStatements() {
+    return statements;
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/NullOp.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/NullOp.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/NullOp.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,40 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import org.mulgara.connection.Connection;
-
-/**
- * An AST element for commands that do not require processing.
- *
- * @created 2007-08-21
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class NullOp extends LocalCommand {
-
-  /**
-   * @see org.mulgara.operation.Command#isUICommand()
-   */
-  public boolean isUICommand() {
-    return false;
-  }
-
-  /**
-   * Do nothing.
-   */
-  public Object execute(Connection conn) throws Exception {
-    return null;
-  }
-
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/NullOp.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/NullOp.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/NullOp.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/NullOp.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,40 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+package org.mulgara.query.operation;
+
+import org.mulgara.connection.Connection;
+
+/**
+ * An AST element for commands that do not require processing.
+ *
+ * @created 2007-08-21
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class NullOp extends LocalCommand {
+
+  /**
+   * @see org.mulgara.operation.Command#isUICommand()
+   */
+  public boolean isUICommand() {
+    return false;
+  }
+
+  /**
+   * Do nothing.
+   */
+  public Object execute(Connection conn) throws Exception {
+    return null;
+  }
+
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Quit.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Quit.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Quit.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,53 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-
-package org.mulgara.query.operation;
-
-import org.mulgara.connection.Connection;
-
-
-/**
- * An AST element for the QUIT command.
- *
- * @created 2007-08-09
- * @author Paul Gearon
- * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
- */
-public class Quit extends LocalCommand {
-  
-  static final String finalMessage = "Exiting.";
-
-  /**
-   * Indicates that this operation is for a UI.
-   * @return <code>true</code> as operation is for UI output only.
-   */
-  public boolean isUICommand() {
-    return true;
-  }
-
-  /**
-   * No specific action to be taken here.  The client needs to know that this message
-   * requires exiting of the main process.
-   */
-  public Object execute(Connection conn) throws Exception {
-    return finalMessage;
-  }
-
-  /**
-   * Indicates that this command is a request to quit.
-   * @return <code>true</code> to indicate that a client should quit.
-   */
-  public boolean isQuitCommand() {
-    return true;
-  }
-}

Copied: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Quit.java (from rev 619, trunk/src/jar/query/java/org/mulgara/query/operation/Quit.java)
===================================================================
--- branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Quit.java	                        (rev 0)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Quit.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -0,0 +1,53 @@
+/*
+ * The contents of this file are subject to the Open Software License
+ * Version 3.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.opensource.org/licenses/osl-3.0.txt
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+ * the License for the specific language governing rights and limitations
+ * under the License.
+ */
+
+package org.mulgara.query.operation;
+
+import org.mulgara.connection.Connection;
+
+
+/**
+ * An AST element for the QUIT command.
+ *
+ * @created 2007-08-09
+ * @author Paul Gearon
+ * @copyright &copy; 2007 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
+ * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a>
+ */
+public class Quit extends LocalCommand {
+  
+  static final String finalMessage = "Exiting.";
+
+  /**
+   * Indicates that this operation is for a UI.
+   * @return <code>true</code> as operation is for UI output only.
+   */
+  public boolean isUICommand() {
+    return true;
+  }
+
+  /**
+   * No specific action to be taken here.  The client needs to know that this message
+   * requires exiting of the main process.
+   */
+  public Object execute(Connection conn) throws Exception {
+    return finalMessage;
+  }
+
+  /**
+   * Indicates that this command is a request to quit.
+   * @return <code>true</code> to indicate that a client should quit.
+   */
+  public boolean isQuitCommand() {
+    return true;
+  }
+}

Deleted: branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Restore.java
===================================================================
--- trunk/src/jar/query/java/org/mulgara/query/operation/Restore.java	2007-12-14 14:03:55 UTC (rev 619)
+++ branches/mgr-73/src/jar/query/java/org/mulgara/query/operation/Restore.java	2008-01-14 07:33:14 UTC (rev 622)
@@ -1,75 +0,0 @@
-/*
- * The contents of this file are subject to the Open Software License
- * Version 3.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.opensource.org/licenses/osl-3.0.txt
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- */
-package org.mulgara.query.operation;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-
-import