[Mulgara-svn] r1208 - in trunk: . src/jar src/jar/client-jrdf src/jar/descriptor src/jar/driver src/jar/krule src/jar/querylang src/jar/querylang/itql src/jar/querylang/java src/jar/querylang/java/org src/jar/querylang/java/org/mulgara src/jar/querylang/java/org/mulgara/itql src/jar/querylang/java/org/mulgara/itql/examples src/jar/querylang/java/org/mulgara/store src/jar/querylang/java/org/mulgara/store/jxunit src/jar/querylang/sablecc src/jar/server-beep src/jar/server-http src/jar/server-local src/jar/sofa src/jar/sparql-protocol src/jar/web

pag at mulgara.org pag at mulgara.org
Sat Aug 30 07:33:22 UTC 2008


Author: pag
Date: 2008-08-30 00:33:19 -0700 (Sat, 30 Aug 2008)
New Revision: 1208

Added:
   trunk/src/jar/querylang/
   trunk/src/jar/querylang/build.xml
   trunk/src/jar/querylang/itql/
   trunk/src/jar/querylang/itql/default-post.itql
   trunk/src/jar/querylang/itql/default-pre.itql
   trunk/src/jar/querylang/java/
   trunk/src/jar/querylang/java/org/
   trunk/src/jar/querylang/java/org/mulgara/
   trunk/src/jar/querylang/java/org/mulgara/itql/
   trunk/src/jar/querylang/java/org/mulgara/itql/Aliasing.java
   trunk/src/jar/querylang/java/org/mulgara/itql/Collaborator.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java
   trunk/src/jar/querylang/java/org/mulgara/itql/Login.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlSession.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java
   trunk/src/jar/querylang/java/org/mulgara/itql/URIUtil.java
   trunk/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java
   trunk/src/jar/querylang/java/org/mulgara/itql/examples/
   trunk/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java
   trunk/src/jar/querylang/java/org/mulgara/itql/package.html
   trunk/src/jar/querylang/java/org/mulgara/store/
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java
   trunk/src/jar/querylang/querylang-build.properties
   trunk/src/jar/querylang/sablecc/
   trunk/src/jar/querylang/sablecc/itql.grammar
Removed:
   trunk/src/jar/itql/
   trunk/src/jar/querylang/build.xml
   trunk/src/jar/querylang/itql/
   trunk/src/jar/querylang/itql/default-post.itql
   trunk/src/jar/querylang/itql/default-pre.itql
   trunk/src/jar/querylang/java/
   trunk/src/jar/querylang/java/org/
   trunk/src/jar/querylang/java/org/mulgara/
   trunk/src/jar/querylang/java/org/mulgara/itql/
   trunk/src/jar/querylang/java/org/mulgara/itql/Aliasing.java
   trunk/src/jar/querylang/java/org/mulgara/itql/Collaborator.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java
   trunk/src/jar/querylang/java/org/mulgara/itql/Login.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlSession.java
   trunk/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java
   trunk/src/jar/querylang/java/org/mulgara/itql/URIUtil.java
   trunk/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java
   trunk/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java
   trunk/src/jar/querylang/java/org/mulgara/itql/examples/
   trunk/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java
   trunk/src/jar/querylang/java/org/mulgara/itql/package.html
   trunk/src/jar/querylang/java/org/mulgara/store/
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java
   trunk/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java
   trunk/src/jar/querylang/querylang-build.properties
   trunk/src/jar/querylang/sablecc/
   trunk/src/jar/querylang/sablecc/itql.grammar
Modified:
   trunk/.classpath
   trunk/build.properties
   trunk/build.xml
   trunk/common.xml
   trunk/src/jar/client-jrdf/build.xml
   trunk/src/jar/descriptor/build.xml
   trunk/src/jar/driver/build.xml
   trunk/src/jar/krule/build.xml
   trunk/src/jar/server-beep/build.xml
   trunk/src/jar/server-http/build.xml
   trunk/src/jar/server-local/build.xml
   trunk/src/jar/sofa/build.xml
   trunk/src/jar/sparql-protocol/build.xml
   trunk/src/jar/web/build.xml
Log:
Merge into the main trunk of the itql module being renamed to querylang. r1200:1207

Modified: trunk/.classpath
===================================================================
--- trunk/.classpath	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/.classpath	2008-08-30 07:33:19 UTC (rev 1208)
@@ -10,11 +10,11 @@
 	<classpathentry kind="src" path="src/jar/descriptor/src/java"/>
 	<classpathentry kind="src" path="src/jar/driver/java"/>
 	<classpathentry kind="src" path="src/jar/dtd/java"/>
-	<classpathentry kind="src" path="src/jar/itql/java"/>
-	<classpathentry kind="src" path="src/jar/itql/sablecc"/>
 	<classpathentry kind="src" path="src/jar/krule/java"/>
 	<classpathentry kind="src" path="src/jar/jrdf/java"/>
 	<classpathentry kind="src" path="src/jar/query/java"/>
+	<classpathentry kind="src" path="src/jar/querylang/java"/>
+	<classpathentry kind="src" path="src/jar/querylang/sablecc"/>
 	<classpathentry kind="src" path="src/jar/resolver/java"/>
 	<classpathentry kind="src" path="src/jar/resolver-distributed/java"/>
 	<classpathentry kind="src" path="src/jar/resolver-file/java"/>

Modified: trunk/build.properties
===================================================================
--- trunk/build.properties	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/build.properties	2008-08-30 07:33:19 UTC (rev 1208)
@@ -74,7 +74,7 @@
 
 # Executable JARs for distribution
 driver.jar        = driver-${mulgara-version}.jar
-itql.jar          = itql-${mulgara-version}.jar
+querylang.jar          = querylang-${mulgara-version}.jar
 mulgara.jar        = mulgara-${mulgara-version}.jar
 mulgara-core.jar  = mulgara-core-${mulgara-version}.jar
 mulgara-lite.jar   = mulgara-lite-${mulgara-version}.jar
@@ -84,10 +84,10 @@
 ant-task.jar      = mulgara-ant-task-${mulgara-version}.jar
 
 junit.results            = ${test.dir}/All-Tests.xml
-itql.results             = ${test.dir}/iTQL-Tests.xml
+querylang.results        = ${test.dir}/QueryLanguage-Tests.xml
 mulgara.results           = ${test.dir}/Mulgara-Tests.xml
 junit.results.tmpdir     = ${test.dir}/alltest
-itql.results.tmpdir      = ${test.dir}/itqltest
+querylang.results.tmpdir      = ${test.dir}/querylangtest
 mulgara.results.tmpdir    = ${test.dir}/mulgaratest
 loadtest.results         = ${test.dir}/All-LoadTests.xml
 loadtest.results.tmpdir  = ${test.dir}/loadtest

Modified: trunk/build.xml
===================================================================
--- trunk/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -24,10 +24,9 @@
   <property file="${jar.src.dir}/descriptor/descriptor-build.properties"/>
   <property file="${jar.src.dir}/driver/driver-build.properties"/>
   <property file="${jar.src.dir}/dtd/dtd-build.properties"/>
-  <property file="${jar.src.dir}/itql/itql-build.properties"/>
   <property file="${jar.src.dir}/jrdf/jrdf-build.properties"/>
   <property file="${jar.src.dir}/query/query-build.properties"/>
-  <!--property file="${jar.src.dir}/rdql/rdql-build.properties"/-->
+  <property file="${jar.src.dir}/querylang/querylang-build.properties"/>
   <property file="${jar.src.dir}/resolver/resolver-build.properties"/>
   <property file="${jar.src.dir}/resolver-null/resolver-null-build.properties"/>
   <property file="${jar.src.dir}/resolver-file/resolver-file-build.properties"/>
@@ -96,10 +95,9 @@
   <import file="${jar.src.dir}/descriptor/build.xml"/>
   <import file="${jar.src.dir}/driver/build.xml"/>
   <import file="${jar.src.dir}/dtd/build.xml"/>
-  <import file="${jar.src.dir}/itql/build.xml"/>
   <import file="${jar.src.dir}/jrdf/build.xml"/>
   <import file="${jar.src.dir}/query/build.xml"/>
-  <!--import file="${jar.src.dir}/rdql/build.xml"/-->
+  <import file="${jar.src.dir}/querylang/build.xml"/>
   <import file="${jar.src.dir}/resolver/build.xml"/>
   <import file="${jar.src.dir}/resolver-null/build.xml"/>
   <import file="${jar.src.dir}/resolver-file/build.xml"/>
@@ -218,22 +216,9 @@
 
     <tstamp/>
 
-    <delete>
-      <fileset dir="${obj.dir}" defaultexcludes="false">
-        <exclude name="jar/itql/**/*"/>
-      </fileset>
-      <dirset dir="${obj.dir}" defaultexcludes="false">
-        <exclude name="jar/itql/*"/>
-      </dirset>
-    </delete>
-    <delete dir="${test.dir}"/>
+    <delete dir="${obj.dir}"/>
     <delete dir="${bin.dir}"/>
-    <delete>
-      <fileset dir="${dist.dir}" defaultexcludes="false">
-        <exclude name="ideSupport.jar"/>
-      </fileset>
-      <dirset dir="${dist.dir}" defaultexcludes="false"/>
-    </delete>
+    <delete dir="${dist.dir}"/>
     <delete dir="${tmp.dir}"/>
     <delete dir="${javadoc.dir}"/>
     <delete dir="${jxtest.dir}"/>
@@ -274,7 +259,7 @@
   <!-- Run JUnit regression (non-load) tests on dbms.jar                   -->
   <!-- =================================================================== -->
   <target name="dbms-test" depends="-prepare-build, uri,
-    driver-jar, itql-jar, query-jar, util-jar, log4j-conf.xml"
+    driver-jar, querylang-jar, query-jar, util-jar, log4j-conf.xml"
     description="runs regression tests on the triple store">
 
     <!-- Set timestamp for CruiseControl's benefit -->
@@ -302,7 +287,7 @@
       <classpath path="${activation.jar}"/>
       <classpath path="${bin.dir}/${query.jar}"/>
       <classpath path="${bin.dir}/${driver.jar}"/>
-      <classpath path="${bin.dir}/${itql.jar}"/>
+      <classpath path="${bin.dir}/${querylang.jar}"/>
       <classpath path="${bin.dir}/${rules.jar}"/>
       <classpath path="${bin.dir}/${server.jar}"/>
       <classpath path="${bin.dir}/${util.jar}"/>
@@ -315,7 +300,7 @@
           excludes="**/*LoadTest.java"/>
         <fileset dir="${src.dir}/jar/driver/java" includes="**/*Test.java"
           excludes="**/*LoadTest.java"/>
-        <fileset dir="${src.dir}/jar/itql/java" includes="**/*Test.java"
+        <fileset dir="${src.dir}/jar/querylang/java" includes="**/*Test.java"
           excludes="**/*LoadTest.java"/>
         <fileset dir="${src.dir}/jar/server/java" includes="**/*Test.java"
           excludes="**/*LoadTest.java"/>
@@ -336,7 +321,7 @@
           depends="ant-task-dist,
                    client-jrdf-dist, content-mbox-dist,
                    content-mp3-dist, content-rdfxml-dist,
-                   descriptor-dist, driver-dist, dtd-dist, itql-dist, jrdf-dist,
+                   descriptor-dist, driver-dist, dtd-dist, querylang-dist, jrdf-dist,
                    store-dist, store-xa-dist, store-nodepool-dist,
                    store-nodepool-memory-dist,
                    store-nodepool-xa-dist, query-dist,
@@ -361,7 +346,7 @@
   <!-- =================================================================== -->
   <!-- Removed server-local, jrdf -->
   <target name="dist"
-          depends="itql-dist, driver-dist, descriptor-dist, mulgara-war,
+          depends="querylang-dist, driver-dist, descriptor-dist, mulgara-war,
                    embedded-dist, lite-dist"
           description="Creates the distribution files">
 
@@ -495,7 +480,7 @@
 
       <attribute name="Main-Class" value="org.mulgara.util.Bootstrap"/>
       <attribute name="Embedded-Jar" value="
-          lib/${query.jar}, lib/${driver.jar}, lib/${itql.jar}, lib/${sparql-int.jar},
+          lib/${query.jar}, lib/${driver.jar}, lib/${querylang.jar}, lib/${sparql-int.jar},
           lib/${rmi.jar},
           lib/${server.jar}, lib/${server-beep.jar}, lib/${server-rmi.jar},
           lib/${util.jar}, lib/${config.jar}, lib/${descriptor.jar}, lib/${server-local.jar},
@@ -528,7 +513,7 @@
   <!-- Creates the lite distribution file for the Embedded Mulgara server   -->
   <!-- =================================================================== -->
   <target name="lite-dist"
-          depends="driver-jar, itql-jar, sparql-int-jar, rules-jar, query-jar, rmi-jar,
+          depends="driver-jar, querylang-jar, sparql-int-jar, rules-jar, query-jar, rmi-jar,
                    server-jar, server-local-jar, server-beep-jar,
                    server-rmi-jar, util-jar, config-jar, dtd-jar, jrdf-jar, ant-task-jar,
                    store-dist, store-xa-dist, store-nodepool-dist,
@@ -582,7 +567,7 @@
                        ${axis.jar}, ${commons-discovery.jar},
                        ${jaxrpc.jar}, ${wsdl4j.jar}"/>
       <zipfileset dir="${bin.dir}" prefix="lib" includes="
-          ${query.jar}, ${driver.jar}, ${itql.jar}, ${sparql-int.jar},
+          ${query.jar}, ${driver.jar}, ${querylang.jar}, ${sparql-int.jar},
           ${rules.jar}, ${rmi.jar},
           ${server.jar}, ${server-beep.jar}, ${server-rmi.jar},
           ${util.jar}, ${config.jar}, ${descriptor.jar}, ${server-local.jar},
@@ -755,7 +740,7 @@
              ant-task-jar, client-jrdf-jar, config-jar,
              content-mbox-jar, content-mp3-jar,
              content-n3-jar, content-rdfxml-jar,
-             itql-jar, sparql-int-jar,
+             querylang-jar, sparql-int-jar,
              doclet.jar, jrdf-jar, store-jar,
              store-xa-jar,
              store-nodepool-jar, store-nodepool-memory-jar,
@@ -851,7 +836,7 @@
       <sourcepath path="${content-rdfxml.src.dir}/java"/>
       <sourcepath path="${driver.src.dir}/java"/>
       <sourcepath path="${dtd.src.dir}/java"/>
-      <sourcepath path="${itql.src.dir}/java"/>
+      <sourcepath path="${querylang.src.dir}/java"/>
       <sourcepath path="${jrdf.src.dir}/java"/>
       <sourcepath path="${krule.src.dir}/java"/>
       <sourcepath path="${rules.src.dir}/java"/>
@@ -893,7 +878,7 @@
       <sourcepath path="${webui.src.dir}/java"/>
       <sourcepath path="${web.src.dir}/java"/>
       <sourcepath path="${obj.dir}/jar/config/java"/>
-      <sourcepath path="${obj.dir}/jar/itql/java"/>
+      <sourcepath path="${obj.dir}/jar/querylang/java"/>
       <sourcepath path="${obj.dir}/jar/query/java"/>
       <!--sourcepath path="${obj.dir}/jar/rdql/java"/-->
       <sourcepath path="${obj.dir}/jar/util/java"/>
@@ -920,7 +905,7 @@
                    content-mp3-javadoc, content-n3-javadoc,
                    content-rdfxml-javadoc,
                    descriptor-javadoc, driver-javadoc, dtd-javadoc,
-                   itql-javadoc, sparql-int-javadoc,
+                   querylang-javadoc, sparql-int-javadoc,
                    store-javadoc, store-xa-javadoc,
                    store-nodepool-javadoc,
                    store-nodepool-memory-javadoc, jrdf-javadoc,
@@ -1024,7 +1009,7 @@
   <!-- =================================================================== -->
   <!-- Starts the iTQL command line tool                                   -->
   <!-- =================================================================== -->
-  <target name="run-itql" depends="itql-dist, uri">
+  <target name="run-itql" depends="querylang-dist, uri">
 
     <java classname="org.mulgara.itql.ItqlSession"
           failonerror="yes">
@@ -1039,7 +1024,7 @@
 
         <pathelement path="${bin.dir}/${query.jar}"/>
         <pathelement path="${bin.dir}/${driver.jar}"/>
-        <pathelement path="${bin.dir}/${itql.jar}"/>
+        <pathelement path="${bin.dir}/${querylang.jar}"/>
         <pathelement path="${bin.dir}/${rules.jar}"/>
         <pathelement path="${bin.dir}/${server.jar}"/>
         <pathelement path="${bin.dir}/${server-http.jar}"/>
@@ -1338,7 +1323,7 @@
   <!-- =================================================================== -->
 
   <target name="stress-test"
-          depends="itql-jar, uri"
+          depends="querylang-jar, uri"
           description="run stress tests the ItqlInterpreterBean">
 
     <java classname="org.mulgara.itql.ItqlInterpreterStressTest" fork="yes" failonerror="no"
@@ -1365,7 +1350,7 @@
 
         <path refid="query-classpath"/>
 
-        <fileset dir="${bin.dir}" includes="${dtd.jar}, ${itql.jar}, ${rules.jar}, ${query.jar},
+        <fileset dir="${bin.dir}" includes="${dtd.jar}, ${querylang.jar}, ${rules.jar}, ${query.jar},
                  ${driver.jar}, ${rmi.jar}, ${server-rmi.jar}"/>
         <fileset dir="${lib.dir}" includes="xerces*.jar, xmlParserAPIs.jar, jxunit*.jar, junit.jar, junitpp.jar"/>
       </classpath>
@@ -1380,7 +1365,7 @@
     depends="-prepare-build, log4j-conf.xml, dist"
     description="Runs regression tests on a Mulgara server">
 
-    <echo message="mulgara-test has not been implemented, run itql-test or dbms-test instead."/-->
+    <echo message="mulgara-test has not been implemented, run querylang-test or dbms-test instead."/-->
 
     <!-- Set timestamp for CruiseControl's benefit -->
     <!--tstamp/>
@@ -1405,7 +1390,7 @@
   <!-- =================================================================== -->
   <target name="mulgara-war"
       description="Builds the Mulgara Semantic Store (Mulgara) WAR"
-      depends="driver-jar, itql-jar, sparql-int-jar, query-jar, rmi-jar, server-jar,
+      depends="driver-jar, querylang-jar, sparql-int-jar, query-jar, rmi-jar, server-jar,
       server-beep-jar, server-rmi-jar, util-jar, config-jar, descriptor-jar, dtd-compile,
       set.host.name, mulgara.war-uptodate"
       unless="mulgara.war-uptodate">
@@ -1431,7 +1416,7 @@
       <lib dir="${lib.dir}" includes="log4j-core-*.jar, icu4j.jar, jena-*.jar, antlr*.jar, beepcore-*.jar,
         lucene*.jar, apache-soap-*.jar, ${joda-time.jar}, ${commons-logging.jar}, ${sesame-model.jar}"/>
       <lib dir="${bin.dir}" includes="${query.jar},
-        ${driver.jar}, ${itql.jar}, ${sparql-int.jar}, ${rules.jar}, ${rmi.jar},
+        ${driver.jar}, ${querylang.jar}, ${sparql-int.jar}, ${rules.jar}, ${rmi.jar},
           ${server.jar}, ${server-beep.jar}, ${server-rmi.jar},
           ${util.jar}, ${config.jar}"/>
       <lib dir="${dist.dir}" includes="expires.txt"/>
@@ -1444,7 +1429,7 @@
        targetfile="${bin.dir}/${mulgara.war}">
 
       <srcfiles dir="${bin.dir}" includes="${query.jar},
-          ${driver.jar}, ${itql.jar}, ${rules.jar}, ${rmi.jar},
+          ${driver.jar}, ${querylang.jar}, ${rules.jar}, ${rmi.jar},
           ${sparql-int.jar},
           ${server.jar}, ${server-beep.jar}, ${server-rmi.jar},
           ${util.jar}, ${config.jar}, ${descriptor.jar}"/>
@@ -1722,7 +1707,7 @@
              content-mbox-jar, content-mp3-jar, content-n3-jar,
              content-rdfxml-jar,
              create-manifest, demo-jar, dtd-jar, driver-jar, dtd-jar,
-             itql-jar, sparql-int-jar,
+             querylang-jar, sparql-int-jar,
              javadoc-dist, jrdf-jar, store-jar, store-xa-jar,
              store-nodepool-jar,
              store-nodepool-memory-jar, store-nodepool-xa-jar,
@@ -1809,7 +1794,7 @@
       <!-- core libraries -->
       <zipfileset src="${bin.dir}/${query.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${driver.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${bin.dir}/${itql.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${bin.dir}/${querylang.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${sparql-int.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${rmi.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${server.jar}" excludes="META-INF/**"/>
@@ -1892,7 +1877,7 @@
              content-mbox-jar, content-mp3-jar, content-n3-jar,
              content-rdfxml-jar,
              demo-jar, driver-jar, dtd-jar,
-             itql-jar, sparql-int-jar,
+             querylang-jar, sparql-int-jar,
              jrdf-jar, store-jar, store-xa-jar,
              store-nodepool-jar,
              store-nodepool-memory-jar, store-nodepool-xa-jar,
@@ -1916,7 +1901,7 @@
       <zipfileset src="${bin.dir}/${client-jrdf.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${query.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${driver.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${bin.dir}/${itql.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${bin.dir}/${querylang.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${sparql-int.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${rmi.jar}" excludes="META-INF/**"/>
       <zipfileset src="${bin.dir}/${server.jar}" excludes="META-INF/**"/>
@@ -2022,7 +2007,7 @@
 
   <target name="client-test"
           depends="client-jrdf-test,
-                   demo-mp3-test, driver-test, itql-test, query-test,
+                   demo-mp3-test, driver-test, querylang-test, query-test,
                    descriptor-test"
           description="Runs client side tests">
   </target>
@@ -2069,9 +2054,9 @@
     description="Builds necessary libraries for using the Eclipse IDE.">
 
      <jar jarfile="${dist.dir}/ideSupport.jar">
-      <zipfileset dir="${obj.dir}/jar/itql/classes" includes="org/mulgara/itql/**"/>
-      <zipfileset dir="${obj.dir}/jar/itql/java" includes="org/mulgara/itql/lexer/lexer.dat"/>
-      <zipfileset dir="${obj.dir}/jar/itql/java" includes="org/mulgara/itql/parser/parser.dat"/>
+      <zipfileset dir="${obj.dir}/jar/querylang/classes" includes="org/mulgara/itql/**"/>
+      <zipfileset dir="${obj.dir}/jar/querylang/java" includes="org/mulgara/itql/lexer/lexer.dat"/>
+      <zipfileset dir="${obj.dir}/jar/querylang/java" includes="org/mulgara/itql/parser/parser.dat"/>
       <zipfileset dir="${obj.dir}/jar/config/classes" includes="org/mulgara/config/**"/>
       <zipfileset dir="${obj.dir}/jar/util/classes" includes="org/mulgara/util/conversion/**"/>
       <zipfileset dir="${obj.dir}/jar/server-rmi/classes" includes="org/mulgara/server/rmi/**"/>

Modified: trunk/common.xml
===================================================================
--- trunk/common.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/common.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -251,7 +251,7 @@
       <sysproperty key="java.io.tmpdir" value="${tmp.dir}"/>
       <sysproperty key="test.dir" value="${test.dir}"/>
       <sysproperty key="admin" value=""/>
-      <sysproperty key="itql.command.log" value="${tmp.dir}/itql.log"/>
+      <sysproperty key="itql.command.log" value="${tmp.dir}/querylang.log"/>
       <sysproperty key="org.mulgara.xml.ResourceDocumentBuilderFactory"
                    value="org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"/>
       <sysproperty key="java.naming.factory.initial"
@@ -315,7 +315,7 @@
       <sysproperty key="java.io.tmpdir" value="${tmp.dir}"/>
       <sysproperty key="test.dir" value="${test.dir}"/>
       <sysproperty key="admin" value=""/>
-      <sysproperty key="itql.command.log" value="${tmp.dir}/itql.log"/>
+      <sysproperty key="itql.command.log" value="${tmp.dir}/querylang.log"/>
       <sysproperty key="org.mulgara.xml.ResourceDocumentBuilderFactory"
                    value="org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"/>
       <sysproperty key="java.naming.factory.initial"
@@ -391,7 +391,7 @@
   <!-- =================================================================== -->
 
   <target name="stress-test"
-          depends="itql-jar, uri"
+          depends="querylang-jar, uri"
           description="run stress tests the ItqlInterpreterBean">
 
     <java classname="org.mulgara.itql.ItqlInterpreterStressTest" fork="yes" failonerror="no"
@@ -418,7 +418,7 @@
 
         <path refid="query-classpath"/>
 
-        <fileset dir="${bin.dir}" includes="${dtd.jar}, ${itql.jar}, ${query.jar},
+        <fileset dir="${bin.dir}" includes="${dtd.jar}, ${querylang.jar}, ${query.jar},
                  ${driver.jar}, ${rmi.jar}, ${server-rmi.jar}"/>
         <fileset dir="${lib.dir}" includes="xerces*.jar, xmlParserAPIs.jar, jxunit*.jar, junit.jar, junitpp.jar"/>
       </classpath>
@@ -470,14 +470,14 @@
       <sysproperty key="file.encoding" value="UTF8"/>
       <sysproperty key="cvs.root" value="${basedir}"/>
       <sysproperty key="log4j.configuration" value="${baseuri}/log4j-conf.xml"/>
-      <sysproperty key="itql.command.log" value="${tmp.dir}/itql.log"/>
+      <sysproperty key="itql.command.log" value="${tmp.dir}/querylang.log"/>
       <sysproperty key="org.mulgara.test" value="${org.mulgara.test}"/>
 
       <classpath>
 
         <path refid="query-classpath"/>
 
-        <fileset dir="${bin.dir}" includes="${dtd.jar}, ${itql.jar},
+        <fileset dir="${bin.dir}" includes="${dtd.jar}, ${querylang.jar},
                                             ${query.jar},
                                             ${driver.jar}, ${rmi.base.jar},
                                             ${server-rmi.jar}"/>

Modified: trunk/src/jar/client-jrdf/build.xml
===================================================================
--- trunk/src/jar/client-jrdf/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/client-jrdf/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -26,7 +26,7 @@
     <pathelement path="${util.dist.dir}/${util.jar}"/>
     <pathelement path="${jrdf.dist.dir}/${jrdf.base.jar}"/>
     <pathelement path="${server-rmi.dist.dir}/${server-rmi.jar}"/>
-    <pathelement path="${itql.dist.dir}/${itql.jar}"/>
+    <pathelement path="${querylang.dist.dir}/${querylang.jar}"/>
     <pathelement path="${rules.dist.dir}/${rules.jar}"/>
     <pathelement path="${lib.dir}/${jrdf.jar}"/>
     <pathelement path="${lib.dir}/${sesame-model.jar}"/>
@@ -61,7 +61,7 @@
   </target>
 
   <target name="client-jrdf-compile"
-          depends="-client-jrdf-prepare, driver-jar, itql-jar, server-jar, jrdf-jar"
+          depends="-client-jrdf-prepare, driver-jar, querylang-jar, server-jar, jrdf-jar"
           description="Compiles all client-jrdf related files included generated
                        source code">
 

Modified: trunk/src/jar/descriptor/build.xml
===================================================================
--- trunk/src/jar/descriptor/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/descriptor/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -24,7 +24,7 @@
     <fileset dir="${lib.dir}" includes="**/**"/>
 
     <fileset dir="${driver.dist.dir}" includes="${driver.jar}" />
-    <fileset dir="${itql.dist.dir}" includes="${itql.jar}" />
+    <fileset dir="${querylang.dist.dir}" includes="${querylang.jar}" />
     <fileset dir="${rules.dist.dir}" includes="${rules.jar}" />
     <fileset dir="${query.dist.dir}" includes="${query.jar}" />
     <fileset dir="${server.dist.dir}" includes="${server.jar}" />
@@ -45,7 +45,7 @@
     <pathelement location="${lib.dir}/${jetty.jar}"/>
 
     <pathelement location="${dist.dir}/${driver.jar}"/>
-    <pathelement location="${dist.dir}/${itql.jar}"/>
+    <pathelement location="${dist.dir}/${querylang.jar}"/>
     <pathelement location="${dist.dir}/${util.jar}"/>
 
     <pathelement location="${server.dist.dir}/${server.jar}"/>
@@ -89,7 +89,7 @@
   </target>
 
   <target name="descriptor-jsp-compile"
-          depends="-descriptor-prepare, driver-jar, itql-jar, server-jar"
+          depends="-descriptor-prepare, driver-jar, querylang-jar, server-jar"
           description="Pre-compiles JSPs">
 
     <!-- Replace basedir -->

Modified: trunk/src/jar/driver/build.xml
===================================================================
--- trunk/src/jar/driver/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/driver/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -93,7 +93,7 @@
   </target>
 
   <target name="driver-dist"
-          depends="driver-jar, driver-jar, itql-jar, query-jar,
+          depends="driver-jar, driver-jar, querylang-jar, query-jar,
                    server-jar, server-beep-jar, server-rmi-jar, util-jar, driver-uptodate"
           unless="driver.uptodate"
           description="Performs all tasks related to finalising this driver
@@ -102,7 +102,7 @@
     <jar jarfile="${dist.dir}/${driver.jar}">
 
       <zipfileset src="${driver.dist.dir}/${driver.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${itql.dist.dir}/${itql.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${querylang.dist.dir}/${querylang.jar}" excludes="META-INF/**"/>
       <zipfileset src="${rules.dist.dir}/${rules.jar}" excludes="META-INF/**"/>
       <zipfileset src="${query.dist.dir}/${query.jar}" excludes="META-INF/**"/>
       <zipfileset src="${server.dist.dir}/${server.jar}" excludes="META-INF/**"/>
@@ -125,7 +125,7 @@
               targetfile="${dist.dir}/${driver.jar}">
 
       <srcfiles dir="${driver.dist.dir}" includes="${driver.jar}"/>
-      <srcfiles dir="${itql.dist.dir}" includes="${itql.jar}"/>
+      <srcfiles dir="${querylang.dist.dir}" includes="${querylang.jar}"/>
       <srcfiles dir="${rules.dist.dir}" includes="${rules.jar}"/>
       <srcfiles dir="${query.dist.dir}" includes="${query.jar}"/>
       <srcfiles dir="${server.dist.dir}" includes="${server.jar}"/>

Modified: trunk/src/jar/krule/build.xml
===================================================================
--- trunk/src/jar/krule/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/krule/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -24,7 +24,7 @@
     <pathelement path="${query.dist.dir}/${query.jar}"/>
     <pathelement path="${driver.dist.dir}/${driver.jar}"/>
     <pathelement path="${util.dist.dir}/${util.jar}"/>
-    <pathelement path="${itql.dist.dir}/${itql.jar}"/>
+    <pathelement path="${querylang.dist.dir}/${querylang.jar}"/>
     <pathelement path="${tuples.dist.dir}/${tuples.jar}"/>
     <pathelement path="${rules.dist.dir}/${rules.jar}"/>
     <pathelement path="${resolver.dist.dir}/${resolver.jar}"/>
@@ -58,7 +58,7 @@
   </target>
 
   <target name="krule-compile"
-          depends="-krule-prepare, driver-jar, itql-jar, rules-jar, tuples-jar, resolver-jar"
+          depends="-krule-prepare, driver-jar, querylang-jar, rules-jar, tuples-jar, resolver-jar"
           description="Compiles all krule related files included generated source code">
 
     <javac destdir="${krule.obj.dir}/classes" debug="on"

Copied: trunk/src/jar/querylang (from rev 1207, branches/mgr-143/src/jar/querylang)

Deleted: trunk/src/jar/querylang/build.xml
===================================================================
--- branches/mgr-143/src/jar/querylang/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,221 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!DOCTYPE project>
-
-<!-- =================================================================== -->
-<!--                       Project definition                            -->
-<!-- =================================================================== -->
-<project name="querylang" default="querylang-jar" basedir="../../..">
-
-  <!-- =================================================================== -->
-  <!--                      Property Definitions                           -->
-  <!-- =================================================================== -->
-
-  <!-- =================================================================== -->
-  <!--                              Imports                                -->
-  <!-- =================================================================== -->
-
-  <!-- =================================================================== -->
-  <!--                          Path Definitions                           -->
-  <!-- =================================================================== -->
-  <path id="querylang-classpath">
-    <path refid="common-classpath"/>
-    <fileset file="${query.dist.dir}/${query.jar}"/>
-    <fileset file="${driver.dist.dir}/${driver.jar}"/>
-    <fileset file="${util.dist.dir}/${util.jar}"/>
-    <fileset file="${rules.dist.dir}/${rules.jar}"/>
-  </path>
-  <path id="querylang-test-classpath">
-    <path refid="querylang-classpath"/>
-    <path refid="driver-classpath"/>
-    <fileset file="${lib.dir}/commons-discovery-1.2.jar"/>
-    <fileset file="${bin.dir}/${rmi.jar}"/>
-    <fileset file="${querylang.dist.dir}/${querylang.jar}"/>
-    <fileset file="${rules.dist.dir}/${rules.jar}"/>
-  </path>
-
-  <target name="querylang-clean" description="Removes all compile generated files for the querylang">
-    <tstamp/>
-    <delete dir="${querylang.obj.dir}"/>
-    <delete dir="${querylang.test.dir}"/>
-    <delete dir="${querylang.dist.dir}"/>
-  </target>
-
-  <target name="-querylang-prepare" description="Creates all directories associated with the querylang's compilation"
-      depends="-prepare-build">
-    <mkdir dir="${querylang.obj.dir}"/>
-    <mkdir dir="${querylang.test.dir}"/>
-    <mkdir dir="${querylang.dist.dir}"/>
-    <mkdir dir="${querylang.obj.dir}/classes"/>
-    <mkdir dir="${querylang.obj.dir}/java"/>
-  </target>
-
-  <target name="gen-querylang-parser" depends="-querylang-prepare, querylang-parser-uptodate, sablecc" unless="querylang-parser-uptodate">
-    <sablecc src="${querylang.src.dir}/sablecc" outputdirectory="${querylang.obj.dir}/java">
-      <include name="itql.grammar"/>
-    </sablecc>
-    <!-- TODO: Add in JavaCC generation -->
-  </target>
-
-  <target name="querylang-parser-uptodate" depends="-prepare-build">
-    <uptodate property="querylang-parser-uptodate"
-        targetfile="${obj.dir}/jar/querylang/java/org/mulgara/itql/analysis/DepthFirstAdapter.java">
-      <srcfiles dir="${querylang.src.dir}/sablecc" includes="itql.grammar"/>
-    </uptodate>
-  </target>
-
-  <target name="-querylang-token-build-label" depends="-querylang-token-build-label-uptodate" unless="querylang.token.build.label.uptodate">
-    <replace file="${querylang.obj.dir}/java/org/mulgara/itql/TqlSession.java" token="@@build.label@@" value="${build.label}"/>
-  </target>
-  <target name="-querylang-token-build-label-uptodate">
-    <uptodate property="querylang.token.build.label.uptodate" targetfile="${querylang.obj.dir}/java/org/mulgara/itql/TqlSession.java">
-      <srcfiles dir="${querylang.src.dir}" includes="**/TqlSession.java"/>
-    </uptodate>
-  </target>
-
-  <target name="querylang-compile" depends="-querylang-prepare, gen-querylang-parser, driver-jar" description="Compiles all query language related files included generated source code">
-    <copy todir="${querylang.obj.dir}/java/" preservelastmodified="yes">
-      <fileset dir="${querylang.src.dir}/java/" includes="**/*.java"/>
-    </copy>
-    <antcall target="-querylang-token-build-label"/>
-    <javac destdir="${querylang.obj.dir}/classes" debug="on" deprecation="on" source="1.5" classpathref="querylang-classpath">
-      <src path="${querylang.obj.dir}/java"/>
-    </javac>
-  </target>
-
-  <!-- This is the manifest for the system that starts the ITQL interpreter by default -->
-  <target name="-querylang-create-manifest">
-    <mkdir dir="${obj.dir}/META-INF"/>
-    <manifest file="${obj.dir}/META-INF/MANIFEST_QUERYLANG_BASE.MF">
-      <attribute name="Main-Class" value="org.mulgara.itql.TqlSession"/>
-    </manifest>
-    <manifest file="${obj.dir}/META-INF/MANIFEST_QUERYLANG_BOOTSTRAP.MF">
-      <attribute name="Main-Class" value="org.mulgara.util.Bootstrap"/>
-      <attribute name="Embedded-Jar" value="${query.jar}, ${driver.jar}, ${querylang.jar},${util.jar}, ${server-beep.jar}, ${server-rmi.jar}, apache-soap-2.2.jar, log4j-1.2.15.jar,jargs-0.2.jar, ${saaj.jar}, ${emory-util.jar}, ${sesame-model.jar}"/>
-      <attribute name="Embedded-Main-Class" value="org.mulgara.itql.TqlSession"/>
-    </manifest>
-  </target>
-
-  <target name="querylang-jar" depends="querylang-compile, -querylang-create-manifest, -querylang-jar-uptodate" unless="querylang.jar.uptodate" description="Creates the querylang's jar/s">
-    <jar jarfile="${querylang.dist.dir}/${querylang.jar}"
-         manifest="${obj.dir}/META-INF/MANIFEST_QUERYLANG_BASE.MF">
-      <fileset dir="${querylang.obj.dir}/classes" excludes="**/*.java"/>
-      <fileset dir="${querylang.obj.dir}/java" includes="**/*.dat"/>
-    </jar>
-  </target>
-
-  <target name="-querylang-jar-uptodate">
-    <uptodate property="querylang.jar.uptodate" targetfile="${querylang.dist.dir}/${querylang.jar}">
-      <srcfiles dir="${querylang.obj.dir}/classes" includes="**/*"/>
-    </uptodate>
-  </target>
-
-  <target name="querylang-dist"
-          depends="querylang-uptodate, querylang-jar, server-beep-jar, server-rmi-jar, sparql-int-jar"
-          unless="querylang.uptodate"
-          description="Performs all tasks related to finalising this querylang and readying it for distribution">
-
-    <mkdir dir="${obj.dir}/META-INF"/>
-
-    <manifest file="${obj.dir}/META-INF/querylang-MANIFEST.MF">
-      <attribute name="Main-Class" value="org.mulgara.itql.TqlSession"/>
-    </manifest>
-
-    <jar jarfile="${dist.dir}/${querylang.jar}"
-         manifest="${obj.dir}/META-INF/querylang-MANIFEST.MF">
-
-      <fileset dir="${conf.dir}" includes="log4j-tql.xml"/>
-      <fileset dir="${querylang.src.dir}/itql"
-               includes="default-pre.itql, default-post.itql"/>
-
-      <zipfileset src="${driver.dist.dir}/${driver.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${querylang.dist.dir}/${querylang.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${query.dist.dir}/${query.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${server-beep.dist.dir}/${server-beep.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${server-rmi.dist.dir}/${server-rmi.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${util.dist.dir}/${util.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${rules.dist.dir}/${rules.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${sparql-int.dist.dir}/${sparql-int.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/beepcore-0.9.08.jar" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/${commons-logging.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/concurrent-1.3.4.jar" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/jargs-0.2.jar" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/${sesame-model.jar}" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/jsr173_07_api.jar" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/jsr173_07_ri.jar" excludes="META-INF/**"/>
-      <zipfileset src="${lib.dir}/log4j-1.2.15.jar" excludes="META-INF/**"/>
-      <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/**"/>
-      <zipfileset src="${lib.dir}/${mulgara-sparql.jar}" excludes="META-INF/**"/>
-    </jar>
-  </target>
-
-  <target name="querylang-uptodate">
-
-    <uptodate property="querylang.uptodate"
-              targetfile="${dist.dir}/${querylang.jar}">
-
-      <srcfiles dir="${querylang.dist.dir}" includes="${querylang.jar}"/>
-      <srcfiles dir="${driver.dist.dir}" includes="${driver.jar}"/>
-      <srcfiles dir="${query.dist.dir}" includes="${query.jar}"/>
-      <srcfiles dir="${sparql-int.dist.dir}" includes="${query.jar}"/>
-      <srcfiles dir="${server-beep.dist.dir}" includes="${server-beep.jar}"/>
-      <srcfiles dir="${server-rmi.dist.dir}" includes="${server-rmi.jar}"/>
-      <srcfiles dir="${util.dist.dir}" includes="${util.jar}"/>
-    </uptodate>
-  </target>
-
-  <target name="querylang-test"
-          depends="querylang-jar, test-data"
-          description="Carries out unit testing for this querylang">
-
-    <!-- start the Mulgara server -->
-    <antcall target="start"/>
-
-    <antcall target="component-test">
-
-      <param name="classpath.id" value="querylang-test-classpath"/>
-      <param name="dir" value="${querylang.src.dir}"/>
-      <param name="jar" value="${querylang.jar}"/>
-    </antcall>
-
-    <!-- stop the Mulgara server -->
-    <antcall target="stop"/>
-  </target>
-
-  <target name="querylang-javadoc"
-          depends="querylang-jar"
-          description="Creates the javadoc for this querylang">
-
-    <antcall target="javadoc">
-
-      <param name="javadoc.package" value="org.mulgara.itql.*,
-                                           org.mulgara.store.*"/>
-      <param name="javadoc.classpath" value="querylang-classpath"/>
-      <param name="javadoc.sourcepath" value="${querylang.src.dir}/java"/>
-    </antcall>
-  </target>
-
-  <target name="querylang-help"
-          description="Displays the help information for this querylang">
-
-    <!-- This is similar to the main project's help except the information
-         is specific to this querylang -->
-
-    <echo message="Welcome to the build script for ${querylang.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 ${querylang.src.dir}/build.xml -projecthelp"/>
-    </java>
-
-  </target>
-</project>

Copied: trunk/src/jar/querylang/build.xml (from rev 1207, branches/mgr-143/src/jar/querylang/build.xml)
===================================================================
--- trunk/src/jar/querylang/build.xml	                        (rev 0)
+++ trunk/src/jar/querylang/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,221 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!DOCTYPE project>
+
+<!-- =================================================================== -->
+<!--                       Project definition                            -->
+<!-- =================================================================== -->
+<project name="querylang" default="querylang-jar" basedir="../../..">
+
+  <!-- =================================================================== -->
+  <!--                      Property Definitions                           -->
+  <!-- =================================================================== -->
+
+  <!-- =================================================================== -->
+  <!--                              Imports                                -->
+  <!-- =================================================================== -->
+
+  <!-- =================================================================== -->
+  <!--                          Path Definitions                           -->
+  <!-- =================================================================== -->
+  <path id="querylang-classpath">
+    <path refid="common-classpath"/>
+    <fileset file="${query.dist.dir}/${query.jar}"/>
+    <fileset file="${driver.dist.dir}/${driver.jar}"/>
+    <fileset file="${util.dist.dir}/${util.jar}"/>
+    <fileset file="${rules.dist.dir}/${rules.jar}"/>
+  </path>
+  <path id="querylang-test-classpath">
+    <path refid="querylang-classpath"/>
+    <path refid="driver-classpath"/>
+    <fileset file="${lib.dir}/commons-discovery-1.2.jar"/>
+    <fileset file="${bin.dir}/${rmi.jar}"/>
+    <fileset file="${querylang.dist.dir}/${querylang.jar}"/>
+    <fileset file="${rules.dist.dir}/${rules.jar}"/>
+  </path>
+
+  <target name="querylang-clean" description="Removes all compile generated files for the querylang">
+    <tstamp/>
+    <delete dir="${querylang.obj.dir}"/>
+    <delete dir="${querylang.test.dir}"/>
+    <delete dir="${querylang.dist.dir}"/>
+  </target>
+
+  <target name="-querylang-prepare" description="Creates all directories associated with the querylang's compilation"
+      depends="-prepare-build">
+    <mkdir dir="${querylang.obj.dir}"/>
+    <mkdir dir="${querylang.test.dir}"/>
+    <mkdir dir="${querylang.dist.dir}"/>
+    <mkdir dir="${querylang.obj.dir}/classes"/>
+    <mkdir dir="${querylang.obj.dir}/java"/>
+  </target>
+
+  <target name="gen-querylang-parser" depends="-querylang-prepare, querylang-parser-uptodate, sablecc" unless="querylang-parser-uptodate">
+    <sablecc src="${querylang.src.dir}/sablecc" outputdirectory="${querylang.obj.dir}/java">
+      <include name="itql.grammar"/>
+    </sablecc>
+    <!-- TODO: Add in JavaCC generation -->
+  </target>
+
+  <target name="querylang-parser-uptodate" depends="-prepare-build">
+    <uptodate property="querylang-parser-uptodate"
+        targetfile="${obj.dir}/jar/querylang/java/org/mulgara/itql/analysis/DepthFirstAdapter.java">
+      <srcfiles dir="${querylang.src.dir}/sablecc" includes="itql.grammar"/>
+    </uptodate>
+  </target>
+
+  <target name="-querylang-token-build-label" depends="-querylang-token-build-label-uptodate" unless="querylang.token.build.label.uptodate">
+    <replace file="${querylang.obj.dir}/java/org/mulgara/itql/TqlSession.java" token="@@build.label@@" value="${build.label}"/>
+  </target>
+  <target name="-querylang-token-build-label-uptodate">
+    <uptodate property="querylang.token.build.label.uptodate" targetfile="${querylang.obj.dir}/java/org/mulgara/itql/TqlSession.java">
+      <srcfiles dir="${querylang.src.dir}" includes="**/TqlSession.java"/>
+    </uptodate>
+  </target>
+
+  <target name="querylang-compile" depends="-querylang-prepare, gen-querylang-parser, driver-jar" description="Compiles all query language related files included generated source code">
+    <copy todir="${querylang.obj.dir}/java/" preservelastmodified="yes">
+      <fileset dir="${querylang.src.dir}/java/" includes="**/*.java"/>
+    </copy>
+    <antcall target="-querylang-token-build-label"/>
+    <javac destdir="${querylang.obj.dir}/classes" debug="on" deprecation="on" source="1.5" classpathref="querylang-classpath">
+      <src path="${querylang.obj.dir}/java"/>
+    </javac>
+  </target>
+
+  <!-- This is the manifest for the system that starts the ITQL interpreter by default -->
+  <target name="-querylang-create-manifest">
+    <mkdir dir="${obj.dir}/META-INF"/>
+    <manifest file="${obj.dir}/META-INF/MANIFEST_QUERYLANG_BASE.MF">
+      <attribute name="Main-Class" value="org.mulgara.itql.TqlSession"/>
+    </manifest>
+    <manifest file="${obj.dir}/META-INF/MANIFEST_QUERYLANG_BOOTSTRAP.MF">
+      <attribute name="Main-Class" value="org.mulgara.util.Bootstrap"/>
+      <attribute name="Embedded-Jar" value="${query.jar}, ${driver.jar}, ${querylang.jar},${util.jar}, ${server-beep.jar}, ${server-rmi.jar}, apache-soap-2.2.jar, log4j-1.2.15.jar,jargs-0.2.jar, ${saaj.jar}, ${emory-util.jar}, ${sesame-model.jar}"/>
+      <attribute name="Embedded-Main-Class" value="org.mulgara.itql.TqlSession"/>
+    </manifest>
+  </target>
+
+  <target name="querylang-jar" depends="querylang-compile, -querylang-create-manifest, -querylang-jar-uptodate" unless="querylang.jar.uptodate" description="Creates the querylang's jar/s">
+    <jar jarfile="${querylang.dist.dir}/${querylang.jar}"
+         manifest="${obj.dir}/META-INF/MANIFEST_QUERYLANG_BASE.MF">
+      <fileset dir="${querylang.obj.dir}/classes" excludes="**/*.java"/>
+      <fileset dir="${querylang.obj.dir}/java" includes="**/*.dat"/>
+    </jar>
+  </target>
+
+  <target name="-querylang-jar-uptodate">
+    <uptodate property="querylang.jar.uptodate" targetfile="${querylang.dist.dir}/${querylang.jar}">
+      <srcfiles dir="${querylang.obj.dir}/classes" includes="**/*"/>
+    </uptodate>
+  </target>
+
+  <target name="querylang-dist"
+          depends="querylang-uptodate, querylang-jar, server-beep-jar, server-rmi-jar, sparql-int-jar"
+          unless="querylang.uptodate"
+          description="Performs all tasks related to finalising this querylang and readying it for distribution">
+
+    <mkdir dir="${obj.dir}/META-INF"/>
+
+    <manifest file="${obj.dir}/META-INF/querylang-MANIFEST.MF">
+      <attribute name="Main-Class" value="org.mulgara.itql.TqlSession"/>
+    </manifest>
+
+    <jar jarfile="${dist.dir}/${querylang.jar}"
+         manifest="${obj.dir}/META-INF/querylang-MANIFEST.MF">
+
+      <fileset dir="${conf.dir}" includes="log4j-tql.xml"/>
+      <fileset dir="${querylang.src.dir}/itql"
+               includes="default-pre.itql, default-post.itql"/>
+
+      <zipfileset src="${driver.dist.dir}/${driver.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${querylang.dist.dir}/${querylang.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${query.dist.dir}/${query.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${server-beep.dist.dir}/${server-beep.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${server-rmi.dist.dir}/${server-rmi.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${util.dist.dir}/${util.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${rules.dist.dir}/${rules.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${sparql-int.dist.dir}/${sparql-int.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/beepcore-0.9.08.jar" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/${commons-logging.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/concurrent-1.3.4.jar" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/jargs-0.2.jar" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/${sesame-model.jar}" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/jsr173_07_api.jar" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/jsr173_07_ri.jar" excludes="META-INF/**"/>
+      <zipfileset src="${lib.dir}/log4j-1.2.15.jar" excludes="META-INF/**"/>
+      <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/**"/>
+      <zipfileset src="${lib.dir}/${mulgara-sparql.jar}" excludes="META-INF/**"/>
+    </jar>
+  </target>
+
+  <target name="querylang-uptodate">
+
+    <uptodate property="querylang.uptodate"
+              targetfile="${dist.dir}/${querylang.jar}">
+
+      <srcfiles dir="${querylang.dist.dir}" includes="${querylang.jar}"/>
+      <srcfiles dir="${driver.dist.dir}" includes="${driver.jar}"/>
+      <srcfiles dir="${query.dist.dir}" includes="${query.jar}"/>
+      <srcfiles dir="${sparql-int.dist.dir}" includes="${query.jar}"/>
+      <srcfiles dir="${server-beep.dist.dir}" includes="${server-beep.jar}"/>
+      <srcfiles dir="${server-rmi.dist.dir}" includes="${server-rmi.jar}"/>
+      <srcfiles dir="${util.dist.dir}" includes="${util.jar}"/>
+    </uptodate>
+  </target>
+
+  <target name="querylang-test"
+          depends="querylang-jar, test-data"
+          description="Carries out unit testing for this querylang">
+
+    <!-- start the Mulgara server -->
+    <antcall target="start"/>
+
+    <antcall target="component-test">
+
+      <param name="classpath.id" value="querylang-test-classpath"/>
+      <param name="dir" value="${querylang.src.dir}"/>
+      <param name="jar" value="${querylang.jar}"/>
+    </antcall>
+
+    <!-- stop the Mulgara server -->
+    <antcall target="stop"/>
+  </target>
+
+  <target name="querylang-javadoc"
+          depends="querylang-jar"
+          description="Creates the javadoc for this querylang">
+
+    <antcall target="javadoc">
+
+      <param name="javadoc.package" value="org.mulgara.itql.*,
+                                           org.mulgara.store.*"/>
+      <param name="javadoc.classpath" value="querylang-classpath"/>
+      <param name="javadoc.sourcepath" value="${querylang.src.dir}/java"/>
+    </antcall>
+  </target>
+
+  <target name="querylang-help"
+          description="Displays the help information for this querylang">
+
+    <!-- This is similar to the main project's help except the information
+         is specific to this querylang -->
+
+    <echo message="Welcome to the build script for ${querylang.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 ${querylang.src.dir}/build.xml -projecthelp"/>
+    </java>
+
+  </target>
+</project>

Copied: trunk/src/jar/querylang/itql (from rev 1207, branches/mgr-143/src/jar/querylang/itql)

Deleted: trunk/src/jar/querylang/itql/default-post.itql
===================================================================
--- branches/mgr-143/src/jar/querylang/itql/default-post.itql	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/itql/default-post.itql	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,5 +0,0 @@
-#
-# Default iTQL interpreter post-loading script
-#
-# $Id: default-post.itql,v 1.8 2005/01/05 04:58:14 newmana Exp $
-#

Copied: trunk/src/jar/querylang/itql/default-post.itql (from rev 1207, branches/mgr-143/src/jar/querylang/itql/default-post.itql)
===================================================================
--- trunk/src/jar/querylang/itql/default-post.itql	                        (rev 0)
+++ trunk/src/jar/querylang/itql/default-post.itql	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,5 @@
+#
+# Default iTQL interpreter post-loading script
+#
+# $Id: default-post.itql,v 1.8 2005/01/05 04:58:14 newmana Exp $
+#

Deleted: trunk/src/jar/querylang/itql/default-pre.itql
===================================================================
--- branches/mgr-143/src/jar/querylang/itql/default-pre.itql	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/itql/default-pre.itql	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,11 +0,0 @@
-#
-# Default iTQL interpreter pre-loading script
-#
-# $Id: default-pre.itql,v 1.8 2005/01/05 04:58:14 newmana Exp $
-#
-
-# set default aliases
-alias <http://purl.org/dc/elements/1.1/> as dcns ;
-alias <http://www.w3.org/1999/02/22-rdf-syntax-ns#> as rdfns ;
-alias <http://www.w3.org/2000/01/rdf-schema#> as rdfsns ;
-alias <http://mulgara.org/mulgara#> as mulgarans ;

Copied: trunk/src/jar/querylang/itql/default-pre.itql (from rev 1207, branches/mgr-143/src/jar/querylang/itql/default-pre.itql)
===================================================================
--- trunk/src/jar/querylang/itql/default-pre.itql	                        (rev 0)
+++ trunk/src/jar/querylang/itql/default-pre.itql	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,11 @@
+#
+# Default iTQL interpreter pre-loading script
+#
+# $Id: default-pre.itql,v 1.8 2005/01/05 04:58:14 newmana Exp $
+#
+
+# set default aliases
+alias <http://purl.org/dc/elements/1.1/> as dcns ;
+alias <http://www.w3.org/1999/02/22-rdf-syntax-ns#> as rdfns ;
+alias <http://www.w3.org/2000/01/rdf-schema#> as rdfsns ;
+alias <http://mulgara.org/mulgara#> as mulgarans ;

Copied: trunk/src/jar/querylang/java (from rev 1207, branches/mgr-143/src/jar/querylang/java)

Copied: trunk/src/jar/querylang/java/org (from rev 1207, branches/mgr-143/src/jar/querylang/java/org)

Copied: trunk/src/jar/querylang/java/org/mulgara (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara)

Copied: trunk/src/jar/querylang/java/org/mulgara/itql (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql)

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/Aliasing.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/Aliasing.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/Aliasing.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,41 +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.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();
-
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/Aliasing.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/Aliasing.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/Aliasing.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/Aliasing.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -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();
+
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/Collaborator.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/Collaborator.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/Collaborator.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,1377 +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;
-
-// Java APIs
-import java.sql.*;
-import java.text.DateFormat;
-import java.util.*;
-
-// Mail api
-import javax.mail.*;
-import javax.mail.internet.*;
-
-// Third party packages
-import org.apache.log4j.*;
-import org.apache.soap.*;
-
-// JRDF
-import org.jrdf.graph.URIReference;
-
-// Locally written
-import org.mulgara.query.Answer;
-import org.mulgara.query.QueryException;
-import org.mulgara.query.TuplesException;
-import org.mulgara.query.Variable;
-import org.mulgara.query.rdf.LiteralImpl;
-import org.mulgara.util.StringUtil;
-
-/**
- * Collaborator contains methods to store and manipulate annotations for the
- * Collaborator Plug-in. All public methods are exposed as SOAP
- * end-points
- *
- * @created 2002-04-08
- *
- * @author <a href="http://staff.PIsoftware.com/tate/">Tate Jones</a>
- *
- * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
- *
- * @copyright &copy; 2002-2003 <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 Collaborator {
-
-  /** 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 */
-  private static String SERVER_NAME = "server1";
-
-  /** 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. */
-  private static ItqlInterpreterBean itqlBean = null;
-
-  /** Default model to use */
-  private final static String MODEL = "collaborator";
-
-  /** Namespace for document */
-  private final static String NS = "http://mulgara.org/mulgara/Annotation#";
-
-  /** Email address predicate */
-  private final static String EMAIL_ADDRESS = NS + "emailAddress";
-
-  /** Nick name predicate */
-  private final static String NICK_NAME = NS + "nickName";
-
-  /** Text predicate */
-  private final static String TEXT = NS + "text";
-
-  /** documentId predicate */
-  private final static String DOCUMENT_ID = NS + "documentId";
-
-  /** annotationId predicate */
-  private final static String ANNOTATION_ID_PREFIX = NS + "annotationId";
-
-  /** annotationId predicate */
-  private final static String DATE = NS + "lastUpdate";
-
-  /** page number predicate */
-  private final static String PAGE_NUMBER = NS + "pageNumber";
-
-  /** x position predicate */
-  private final static String X_POSITION = NS + "xPosition";
-
-  /** y position predicate */
-  private final static String Y_POSITION = NS + "yPosition";
-
-  /** x anchor predicate */
-  private final static String X_ANCHOR = NS + "xAnchor";
-
-  /** y anchor predicate */
-  private final static String Y_ANCHOR = NS + "yAnchor";
-
-  /** height predicate */
-  private final static String HEIGHT = NS + "height";
-
-  /** width predicate */
-  private final static String WIDTH = NS + "width";
-
-  /** Access key prefix */
-  private final static String KEY_PREFIX = NS + "key";
-
-  /** 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 + ">;";
-
-  /** Delete the collaboration model */
-  private final static String DROP_MODEL = "drop <" + SERVER + MODEL + ">;";
-
-  /** Check for registration */
-  private final static String CHECK_REGISTRATION =
-      "select $key from <" + SERVER + MODEL + "> " + "where $key <" +
-      EMAIL_ADDRESS + "> <mailto:~01> ;";
-
-  /** 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 */
-  private final static String CHECK_ACCESS_KEY =
-      "select $emailaddress from <" + SERVER + MODEL + "> " + "where <" +
-      KEY_PREFIX + "~01> $emailaddress <mailto:~02> ;";
-
-  /** Create annotation */
-  private final static String INSERT_ANNOTATION =
-      "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + EMAIL_ADDRESS +
-      "> <mailto:~02> into <" + SERVER + MODEL + ">; " + "insert <" +
-      ANNOTATION_ID_PREFIX + "~01> <" + NICK_NAME + "> '~03' into <" + SERVER +
-      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + TEXT +
-      "> '~04' into <" + SERVER + MODEL + ">; " + "insert <" +
-      ANNOTATION_ID_PREFIX + "~01> <" + PAGE_NUMBER + "> '~05' into <" + SERVER +
-      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + X_POSITION +
-      "> '~06' into <" + SERVER + MODEL + ">; " + "insert <" +
-      ANNOTATION_ID_PREFIX + "~01> <" + Y_POSITION + "> '~07' into <" + SERVER +
-      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + X_ANCHOR +
-      "> '~08' into <" + SERVER + MODEL + ">; " + "insert <" +
-      ANNOTATION_ID_PREFIX + "~01> <" + Y_ANCHOR + "> '~09' into <" + SERVER +
-      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + HEIGHT +
-      "> '~10' into <" + SERVER + MODEL + ">; " + "insert <" +
-      ANNOTATION_ID_PREFIX + "~01> <" + WIDTH + "> '~11' into <" + SERVER +
-      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + DATE +
-      "> '~12' into <" + SERVER + MODEL + ">; " + "insert <" +
-      ANNOTATION_ID_PREFIX + "~01> <" + DOCUMENT_ID + "> '~13' into <" + SERVER +
-      MODEL + ">; ";
-
-  /** 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 */
-  private final static String DELETE_ANNOTATION_STATEMENT =
-      "delete <" + ANNOTATION_ID_PREFIX + "~01> <~02> ~03 from <" + SERVER +
-      MODEL + ">;";
-
-  /** Retrieve all annotations */
-  private final static String RETRIEVE_ANNOTATIONS =
-      "select $annotationId $emailaddress $nickname $text $pageno " +
-      "$x $y $xanchor $yanchor $height $width $lastupdated $documentid " +
-      "from <" + SERVER + MODEL + "> " + "where $annotationId <" + DOCUMENT_ID +
-      "> '~01' and " + "$annotationId <" + EMAIL_ADDRESS +
-      "> $emailaddress and " + "$annotationId <" + NICK_NAME +
-      "> $nickname and " + "$annotationId <" + TEXT + "> $text and " +
-      "$annotationId <" + PAGE_NUMBER + "> $pageno and " + "$annotationId <" +
-      X_POSITION + "> $x and " + "$annotationId <" + Y_POSITION + "> $y and " +
-      "$annotationId <" + X_ANCHOR + "> $xanchor and " + "$annotationId <" +
-      Y_ANCHOR + "> $yanchor and " + "$annotationId <" + HEIGHT +
-      "> $height and " + "$annotationId <" + WIDTH + "> $width and " +
-      "$annotationId <" + DATE + "> $lastupdated and " + "$annotationId <" +
-      DOCUMENT_ID + "> $documentid ;";
-
-  /** Method identifier used for transaction naming */
-  private static final String EXECUTE_COMMAND_TX = "executeCommand";
-
-  /** 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 */
-  DateFormat dateFormat = DateFormat.getInstance();
-
-  /** 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<String,Long> lastChecked = new HashMap<String,Long>();
-
-  /**
-   * The Collaborator will create the ITQL interpreter bean.
-   */
-  public Collaborator() {
-
-    if (itqlBean == null) {
-
-      itqlBean = new ItqlInterpreterBean();
-
-      //Has the server name been determined
-      if (SERVER.length() == 0) log.fatal("Unable to determine localhost name");
-
-      try {
-        initializeModel();
-      } catch (Exception ex) {
-        log.fatal("Unable to initialize collaboration model", ex);
-      }
-    }
-  }
-
-
-  /**
-   * Closes the underlying itql interpreter bean.
-   */
-  public void close() {
-    if (itqlBean != null) {
-      itqlBean.close();
-      itqlBean = null;
-    }
-  }
-
-  /**
-   * Send an email message via SMTP.
-   *
-   * @param from The From address.
-   * @param to The To address.
-   * @param subject The email subject
-   * @param content The email content
-   */
-  private static void sendEmail(String from, String to, String subject,
-                                String content) {
-
-    if (log.isDebugEnabled()) {
-
-      log.debug("sending email from :" + from + " to :" + to + eol +
-          "subject :" + subject + eol + "Content :" + content);
-    }
-
-    //Check for smtp server setting
-    Properties props = System.getProperties();
-
-    if ((props.get("mail.smtp.host") == null) ||
-        (((String) props.get("mail.smtp.host")).length() == 0)) {
-
-      log.warn("unable to send email from :" + from + " to :" + to + eol +
-          "subject :" + subject + eol + "Content :" + content +
-          " - SMTP server not configured");
-
-      return;
-    }
-
-    try {
-
-      // get the default Session
-      javax.mail.Session session =
-          javax.mail.Session.getDefaultInstance(props, null);
-
-      // Set up the to address
-      Address[] toAddress = InternetAddress.parse(to, false);
-
-      // create a message
-      Message message = new MimeMessage(session);
-
-      message.setFrom(new InternetAddress(from));
-
-      message.setSubject(subject);
-      message.setHeader("X-Mailer", "Collaborator Registration");
-      message.setSentDate(new java.util.Date());
-      message.setRecipients(Message.RecipientType.TO, toAddress);
-      message.setText(content);
-
-      // Send newMessage
-      Transport.send(message);
-    } catch (NoSuchProviderException nex) {
-
-      log.error("Cannot send email", nex);
-    } catch (AddressException ex) {
-
-      log.error("Cannot send email", ex);
-    } catch (MessagingException mex) {
-
-      log.error("Cannot send email", mex);
-    }
-  }
-
-  /**
-   * Retrieve a URL from the server based on a specific client request.
-   *
-   * The client will open a new web browser and read the contents of the URL.
-   * This will method will be used to display messages to user.
-   *
-   * @param emailAddress user performing the request
-   * @param key the current access
-   * @param requestType types of requests are:
-   *      <dl>
-   *      <dt>welcome</dt>    <dd>returns a URL for a welcome page</dd>
-   *      <dt>help</dt>       <dd>returns a URL for a help page</dd>
-   *      <dt>invalidkey</dt> <dd>returns a URL for an invalid key page</dd>
-   *      <dt>keyexpired</dt> <dd>returns a URL for an expired key page</dd>
-   *      <dt>invalidemailkey</dt>
-   *        <dd>returns a URL for an invalid email and key match</dd>
-   *      <dt>reports</dt>    <dd>returns a URL for a reports page</dd>
-   *      </dl>
-   * @return the URL to be viewed
-   * @throws SOAPException  Description of Exception
-   */
-  public String getURL(String emailAddress, String key, String requestType)
-    throws SOAPException {
-
-    return "";
-  }
-
-  /**
-   * Perform a registation of a new user. A successful registration will result
-   * in an email been sent containing an access key to initiate the plug-in for
-   * a set period. ?All details are recorded in the Mulgara database.
-   *
-   * @param emailAddress ?email address to send the access key to
-   * @param nickName ? the user name to be registered
-   * @return Description of the Returned Value
-   * @throws SOAPException excepted errors are :emailAddress and/or nickName
-   *      have not been supplied, invalid email address, email address has
-   *      already been registered, error sending email
-   */
-  public synchronized boolean register(String emailAddress, String nickName) throws
-      SOAPException {
-
-    boolean registered = false;
-
-    //Check supplied parameters
-    if ((emailAddress == null) ||
-        (nickName == null) ||
-        (emailAddress.length() == 0) ||
-        (nickName.length() == 0)) {
-
-      log.warn("Null paramaters supplied for email address or nickname");
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Email address and nick name must be supplied");
-    }
-
-    //TODO : validate email address
-    //Check for existing registration
-    if (executeCommand(CHECK_REGISTRATION, new String[] {emailAddress}, 0, false)) {
-
-      //new registration required
-      // TODO : create a better access key
-      String key = String.valueOf(System.currentTimeMillis());
-
-      //For testing purposes only!!! see unit tests
-      lastAccessKeyCreated = key;
-
-      //TODO : Calculate expiry date
-      registered = executeCommand(INSERT_REGISTRATION, new String[] {key, emailAddress, nickName},
-                              "Successfully inserted", true);
-
-      //Send an email with the registration key
-      if (registered) {
-        sendEmail("foo at localhost", emailAddress,
-                       "Collaborator Registration",
-                       "Welcome to Mulgara Collaborator. Your access key is " + key);
-      }
-    } else {
-
-      log.warn("Existing registration already exists for " + emailAddress);
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Your Email address has already been registered");
-    }
-
-    return registered;
-  }
-
-  /**
-   * Check for a valid access key for the plug-in. Confirms the access key is
-   * valid for the supplied email address and the access period has not been
-   * exceed. ?
-   *
-   * @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 ?
-   */
-  public boolean checkAccessKey(String key, String emailAddress) throws SOAPException {
-
-    boolean accessOk = false;
-
-    // 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");
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Email address and key name must be supplied");
-    }
-
-    //Check for the access key
-    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");
-      }
-
-      accessOk = true;
-    } else {
-      log.warn("Invaild access key :" + key + " for email address :" + emailAddress);
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Invaild access key :" + key + " for email address :" + emailAddress);
-    }
-
-    return accessOk;
-  }
-
-  /**
-   * Adds an annotation to a specified document.
-   *
-   * A successful addition will result in an unique annotation id returned.
-   * An annotation contains the following details.
-   *
-   * @param emailAddress  emailAddress user performing the request
-   * @param key           the current access key
-   * @param nickName      nickName the user adding the annotation
-   * @param documentId    documentId unique identifier for the document
-   * @param text          the annotation text
-   * @param pageNo        page number of the annotation
-   * @param xAnchor       x position of the annotation
-   * @param yAnchor       y position of the annotation
-   * @param x             visual x position of the annotation text box
-   * @param y             visual y position of the annotation text box
-   * @param height        visual height of the annotation text box
-   * @param width         visual width of the annotation text box
-   * @return returns a non blank annotationId
-   * @throws SOAPException excepted errors are:
-   *   <ul><li>key is invalid</li>
-   *       <li>key has expired</li>
-   *       <li>invalid parameters supplied</li></ul>
-   */
-  public synchronized String addAnnotation(String emailAddress,
-                                           String key,
-                                           String nickName,
-                                           String documentId,
-                                           String text,
-                                           String pageNo,
-                                           String xAnchor,
-                                           String yAnchor,
-                                           String x,
-                                           String y,
-                                           String height,
-                                           String width) throws SOAPException {
-
-    return addAnnotation(emailAddress, key, nickName, documentId, text,
-                         pageNo, xAnchor, yAnchor, x, y, height, width, true);
-  }
-
-  /**
-   * Remove an annotation from a specified document ?
-   *
-   * @param emailAddress email address of user performing the request
-   * @param key access key for the request email address
-   * @param documentId the document containing the annotation
-   * @param annotationId the annotation to be removed
-   * @return returns true if successful
-   * @throws SOAPException Exceptions are : emailAddress and key do not match,
-   *      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 {
-
-    return removeAnnotation(emailAddress, key, documentId, annotationId, true);
-  }
-
-  /**
-   * Edit an exisiting annotation ?
-   *
-   * @param emailAddress emailAddress user performing the request
-   * @param key the current access key
-   * @param nickName nickName the user adding the annotation
-   * @param documentId documentId unique identifier for the document
-   * @param annotationId Description of Parameter
-   * @param text the annotation text
-   * @param pageNo page number of the annotation
-   * @param xAnchor x position of the annotation
-   * @param yAnchor y position of the annotation
-   * @param x visual x position of the annotation text box
-   * @param y visual y position of the annotation text box
-   * @param height visual height of the annotation text box
-   * @param width visual width of the annotation text box
-   * @return returns a non blank annotationId
-   * @throws SOAPException excepted errors are : key is invaild, key has
-   *      expired, invalid parameters supplied ?
-   */
-  public synchronized String editAnnotation(String emailAddress, String key,
-                                            String nickName, String documentId,
-                                            String annotationId, String text,
-                                            String pageNo, String xAnchor,
-                                            String yAnchor, String x, String y,
-                                            String height, String width) throws
-      SOAPException {
-
-    boolean added = false;
-
-    // Check the the access key for this user.
-    // Will throw an exception if the access key is incorrect
-    checkAccessKey(key, emailAddress);
-
-    //Check parameters
-    if ( (documentId == null) ||
-        (documentId.length() == 0) ||
-        (annotationId == null) ||
-        (annotationId.length() == 0) ||
-        (pageNo == null) ||
-        (pageNo.length() == 0) ||
-        (xAnchor == null) ||
-        (xAnchor.length() == 0) ||
-        (yAnchor == null) ||
-        (yAnchor.length() == 0) ||
-        (x == null) ||
-        (x.length() == 0) ||
-        (y == null) ||
-        (y.length() == 0) ||
-        (height == null) ||
-        (height.length() == 0) ||
-        (width == null) ||
-        (width.length() == 0)) {
-
-      log.warn("Invalid paramaters supplied for annotation");
-
-      SOAPException se =
-          new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Invalid paramaters supplied for annotation");
-      throw se;
-    }
-
-    //Correct the text if null
-    if (text == null) {
-
-      text = "";
-    }
-
-    // Commence a new transaction for the removing and
-    // adding of a new annotation.
-    beginTransaction("editAnnotation");
-
-    try {
-
-      //Remove the annotation
-      if (removeAnnotation(emailAddress, key, documentId, annotationId, false)) {
-
-        //Add the modified annotation
-        annotationId =
-            addAnnotation(emailAddress, key, nickName, documentId, text, pageNo,
-                          xAnchor, yAnchor, x, y, height, width, false);
-
-        //Check the result
-        added = (annotationId.length() > 0);
-      }
-    } catch (SOAPException ex) {
-
-      //Rollback the transaction
-      rollback("editAnnotation");
-
-      // re-throw the exception
-      throw ex;
-    }
-
-    //Check for a new annotation
-    if (!added) {
-
-      //Rollback the transaction
-      rollback("editAnnotation");
-
-      log.warn("Unable to edit annotation documentId :" + documentId +
-               " annotationId :" + annotationId);
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER,
-                            "Unable to edit annotation");
-    } else {
-
-      // Commit the changes
-      commit("editAnnotation");
-
-      // the flag the update document
-      documentHasUpdated(documentId);
-    }
-
-    return annotationId;
-  }
-
-  /**
-   * Retrieve all annotations for a specified docoument
-   *
-   * @param emailAddress emailAddress user performing the request
-   * @param key the current access key
-   * @param documentId unique identifier for the document
-   * @return Description of the Returned Value
-   * @throws SOAPException errors are : emailAddress and key do not match, key
-   *      is invalid, key has expired, invalid parameters supplied, invalid
-   *      documentId supplied
-   */
-  public synchronized String retrieveAnnotations(
-      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
-    checkAccessKey(key, emailAddress);
-
-    //Check parameters
-    if ((documentId == null) || (documentId.length() == 0)) {
-
-      log.warn("Invalid paramaters supplied for retrieving annotations");
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Invalid paramaters supplied for retrieving annotations");
-    }
-
-    String results = "";
-
-    //Subsitute the parameter into the query
-    String query = StringUtil.substituteStrings(RETRIEVE_ANNOTATIONS, documentId);
-
-    if (log.isDebugEnabled()) log.debug("Executing query :" + query);
-
-    //Issue the query
-    try {
-      results = decode(itqlBean.executeQueryToString(query));
-    } catch (Exception ex) {
-
-      log.error("Unable to retrieve annotations for documentId :" + documentId, ex);
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to retrieve annotations: " + ex.getMessage(), ex);
-    }
-
-    // track the document retrieval
-    documentHasBeenRetrieved(documentId, emailAddress);
-
-    return results;
-  }
-
-  /**
-   * Check for annotation updates after a specified date and time.
-   *
-   * @param emailAddress emailAddress user performing the request
-   * @param key the current access key
-   * @param documentId unique identifier for the document
-   * @return return true if updates have been made
-   * @throws SOAPException errors are : emailAddress and key do not match, key
-   *      is invalid, key has expired, invalid parameters supplied, invalid
-   *      documentId supplied
-   */
-  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
-    checkAccessKey(key, emailAddress);
-
-    // Check parameters
-    if ((documentId == null) || (documentId.length() == 0)) {
-      log.warn("Invalid paramaters supplied for retrieving annotations");
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for retrieving annotations");
-    }
-
-    return hasDocumentUpdated(documentId, emailAddress);
-  }
-
-  /**
-   * 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
-   * @throws SQLException Unable to interate over the model details
-   * @throws SOAPException EXCEPTION TO DO
-   */
-  public synchronized boolean initializeModel() throws QueryException,
-      SQLException, SOAPException {
-
-    boolean initialized = false;
-
-    try {
-      // ignore string output
-      itqlBean.executeQueryToString(CHECK_MODEL);
-    } catch (Exception ex) {
-
-      ex.printStackTrace();
-    }
-
-    String model = null;
-
-    for (Object obj: itqlBean.executeQueryToList(CHECK_MODEL)) {
-
-      if (obj instanceof Answer) {
-
-        Answer answer = (Answer)obj;
-
-        try {
-          //reset cursor
-          answer.beforeFirst();
-
-          while (answer.next()) {
-
-            model = ((URIReference)answer.getObject(answer.getColumnIndex(new Variable("model")))).getURI().toString();
-
-            if (log.isDebugEnabled()) log.debug("Found model :" + model);
-
-            int pos = model.indexOf("#");
-
-            if (pos >= 0) {
-
-              if (log.isDebugEnabled()) log.debug("Testing model :" + model.substring(pos + 1));
-              initialized = (model.substring(pos + 1).equals(MODEL));
-            }
-          }
-        } catch (TuplesException e) {
-          throw new QueryException("Couldn't initialize model", e);
-        }
-      } else {
-
-        if (obj instanceof String) {
-
-          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);
-        }
-      }
-    }
-
-    if (initialized == false) {
-      // Model has not been initialized
-      initialized = createModel();
-    } else {
-      log.debug("Collaborator model already initialized at " + SERVER + MODEL);
-    }
-
-    return initialized;
-  }
-
-  /**
-   * Creates a new collaborator model
-   *
-   * @return returns true if successful
-   * @throws SOAPException Error creating the model on the server
-   */
-  public synchronized boolean createModel() throws SOAPException {
-
-    log.warn("creating model " + SERVER + MODEL);
-    return executeCommand(CREATE_MODEL, "Successfully created graph", false);
-  }
-
-  /**
-   * Drops a collaboration model
-   *
-   * @return returns true is sucessful
-   * @throws SOAPException EXCEPTION TO DO
-   */
-  public synchronized boolean dropModel() throws SOAPException {
-
-    log.warn("dropping model " + SERVER + MODEL);
-    return executeCommand(DROP_MODEL, "Successfully dropped graph", false);
-  }
-
-  /**
-   * Test method for SOAP calls
-   *
-   * @return a success message
-   */
-  public String test() {
-
-    return "test";
-  }
-
-  /**
-   * Remove an annotation from a specified document ?
-   *
-   * @param emailAddress email address of user performing the request
-   * @param key access key for the request email address
-   * @param documentId the document containing the annotation
-   * @param annotationId the annotation to be removed
-   * @param trans insert method into a transaction
-   * @return returns true if successful
-   * @throws SOAPException Exceptions are : emailAddress and key do not match,
-   *      key is invaild, key has expired, invalid parameters supplied,
-   *      annotation does not exist
-   */
-  private boolean removeAnnotation(String emailAddress, String key,
-                                   String documentId, String annotationId,
-                                   boolean trans) throws SOAPException {
-
-    boolean removed = false;
-
-    // Check the the access key for this user.
-    // Will throw an exception if the access key is incorrect
-    if (trans) checkAccessKey(key, emailAddress);
-
-    //Check parameters
-    if ((documentId == null) ||
-        (documentId.length() == 0) ||
-        (annotationId == null) ||
-        (annotationId.length() == 0)) {
-
-      log.warn("Invalid paramaters supplied for annotation removal");
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for annotation removal");
-    }
-
-    //Retrieve the annotation
-    Answer annotation = retrieveAnnotation(documentId, annotationId);
-
-    if (annotation != null) {
-
-      String predicate = null;
-      String object = null;
-
-      //Begin a transaction to remove the statements
-      if (trans) beginTransaction(REMOVE_ANNOTATION_TX);
-
-      try {
-
-        //Extract the predicate and object from the resultSet
-        annotation.beforeFirst();
-
-        //Iterate over the rows
-        while (annotation.next()) {
-
-          //grab the predicate
-          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 = "'" + encode(((LiteralImpl) annotation.getObject(objectIndex)).getLexicalForm()) + "'";
-          } else if (annotation.getObject(objectIndex) instanceof URIReference) {
-
-            object = "<" + ((URIReference)annotation.getObject(objectIndex)).getURI() + ">";
-          }
-
-          String[] removalParams = new String[] {annotationId, predicate, object};
-          
-          // delete the annotation statement
-          removed = executeCommand(DELETE_ANNOTATION_STATEMENT,removalParams, "Successfully", false);
-
-          if (!removed) {
-
-            log.warn("Unable to remove annotation statement documentId :" +
-                     documentId + " annotationId :" + annotationId +
-                     " predicate :" +
-                     predicate + " object :" + object);
-            throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to remove annotation");
-          } else {
-
-            // the flag the update document
-            documentHasUpdated(documentId);
-          }
-        }
-
-        // Commit the deletions
-        if (trans) commit(REMOVE_ANNOTATION_TX);
-
-      } catch (TuplesException ex) {
-        // Rollback the transaction
-        if (trans) rollback(REMOVE_ANNOTATION_TX);
-
-        log.error("Unable to locate annotation for removal documentId :" +
-                  documentId + " annotationId :" + annotationId, ex);
-
-        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);
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to locate annotation for removal");
-    }
-
-    return removed;
-  }
-
-  /**
-   * Adds an annotation to a specified document.
-   *
-   * A successful addition will result in a unique annotation id returned.
-   * An annotation contains the following details:
-   *
-   * @param emailAddress emailAddress user performing the request
-   * @param key the current access key
-   * @param nickName nickName the user adding the annotation
-   * @param documentId documentId unique identifier for the document
-   * @param text the annotation text
-   * @param pageNo page number of the annotation
-   * @param xAnchor x position of the annotation
-   * @param yAnchor y position of the annotation
-   * @param x visual x position of the annotation text box
-   * @param y visual y position of the annotation text box
-   * @param height visual height of the annotation text box
-   * @param width visual width of the annotation text box
-   * @param trans will this method be contained in a transaction
-   * @return returns a non blank annotationId
-   * @throws SOAPException excepted errors are:
-   *   <ul>
-   *   <li>key is invalid</li>
-   *   <li>key has expired</li>
-   *   <li>invalid parameters supplied</li>
-   *   </ul>
-   */
-  private String addAnnotation(String emailAddress, String key,
-                               String nickName, String documentId, String text,
-                               String pageNo,
-                               String xAnchor, String yAnchor, String x,
-                               String y, String height,
-                               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) checkAccessKey(key, emailAddress);
-
-    // Check parameters
-    if ((documentId == null) ||
-        (documentId.length() == 0) ||
-        (pageNo == null) ||
-        (pageNo.length() == 0) ||
-        (xAnchor == null) ||
-        (xAnchor.length() == 0) ||
-        (yAnchor == null) ||
-        (yAnchor.length() == 0) ||
-        (x == null) ||
-        (x.length() == 0) ||
-        (y == null) ||
-        (y.length() == 0) ||
-        (height == null) ||
-        (height.length() == 0) ||
-        (width == null) ||
-        (width.length() == 0)) {
-
-      log.warn("Invalid paramaters supplied for annotation");
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for annotation");
-    }
-
-    // Correct the text if null
-    if (text == null) text = "";
-
-    // Create the supporting attributes
-    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
-    String lastUpdated = dateFormat.format(cal.getTime());
-
-    // 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);
-    }
-
-    // Start a transaction for all the inserts
-    if (trans) beginTransaction(ADD_ANNOTATION_TX);
-
-    String[] annotationParams = new String[] {
-        annotationId, emailAddress, nickName, encode(text), pageNo,
-        xAnchor, yAnchor, x, y, height, width, lastUpdated, documentId
-    };
-
-    // Clear the annotationId if unsuccessful - handling transactions at this level
-    if (!executeCommand(INSERT_ANNOTATION, annotationParams, "Successfully inserted", false)) {
-
-      annotationId = "";
-
-      // Rollback the inserts
-      if (trans) rollback(ADD_ANNOTATION_TX);
-
-    } else {
-
-      // Commit the inserts
-      if (trans) commit(ADD_ANNOTATION_TX);
-
-      // the flag the update document
-      documentHasUpdated(documentId);
-    }
-
-    return annotationId;
-  }
-
-  /**
-   * Execute an iTQL query and checks for a specific response
-   *
-   * @param command iTQLQuery
-   * @param substituteArray Description of Parameter
-   * @param rows the expected rows to be returned
-   * @param trans Insert command within a transaction
-   * @return returns true if the expect result is found in the response
-   * @throws SOAPException EXCEPTION TO DO
-   */
-  private boolean executeCommand(String command, String[] substituteArray,
-                                 int rows, boolean trans) throws SOAPException {
-
-    return executeCommand(command, substituteArray, String.valueOf(rows), trans);
-  }
-
-  /**
-   * Execute an iTQL query and checks for a specific response
-   *
-   * @param command iTQLQuery
-   * @param substituteArray Description of Parameter
-   * @param expectedResult the expected result
-   * @param trans Insert command within a transaction
-   * @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 {
-
-    boolean successful = false;
-
-    //Perform any subsitutions
-    if (substituteArray != null) {
-      command = StringUtil.substituteStrings(command, substituteArray);
-    }
-
-    String message = null;
-
-    if (log.isDebugEnabled()) log.debug("Executing command :" + command);
-
-    // Commence a new transaction if required
-    if (trans) beginTransaction(EXECUTE_COMMAND_TX);
-
-    // Issue the itql command
-    for (Object obj: itqlBean.executeQueryToList(command)) {
-
-      // Is the result a message?
-      if (obj instanceof String) {
-
-        message = (String)obj;
-
-        if (log.isDebugEnabled()) log.debug("returned message :" + message);
-
-        // Check the outcome against the expect result
-        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 answer?
-      if (obj instanceof Answer) {
-
-        try {
-
-          // Check the number of rows returned
-          long solutionCount = ((Answer)obj).getRowUpperBound();
-
-          if (log.isDebugEnabled()) log.debug("found answer :" + solutionCount);
-
-          message = String.valueOf(solutionCount);
-
-          // Check the outcome against the expect result
-          successful = ((message != null) && (message.indexOf(expectedResult) >= 0));
-
-          // break if failure occurs
-          if (!successful) break;
-
-        } catch (TuplesException ex) {
-
-          log.error("Error executing command :" + command, ex);
-          // Rollback the changes
-          if (trans) rollback(EXECUTE_COMMAND_TX);
-          return false;
-        }
-      }
-    }
-
-    // Commit the changes whether successful or not
-    if (trans) commit(EXECUTE_COMMAND_TX);
-
-    if (log.isDebugEnabled()) {
-      log.debug("Command :" + command + "message :" + message + " result :" + successful);
-    }
-
-    return successful;
-  }
-
-  /**
-   * Execute iTQL command and checks for a specific response
-   *
-   * @param command iTQL command
-   * @param expectedResult expected result to be checked
-   * @param trans Insert command within a transaction
-   * @return returns the resultSet null means no rows were found
-   * @throws SOAPException EXCEPTION TO DO
-   */
-  private boolean executeCommand(String command, String expectedResult,
-                                 boolean trans) throws SOAPException {
-
-    return executeCommand(command, null, expectedResult, trans);
-  }
-
-  /**
-   * Retrieve all statements for a specific annotationId
-   *
-   * @param documentId unique documentId
-   * @param annotationId AnnotationId for a document
-   * @return Return a resultSet null for no rows
-   */
-  private Answer retrieveAnnotation(String documentId, String annotationId) {
-
-    //Subsitute the parameter into the query
-    String query =
-        StringUtil.substituteStrings(RETRIEVE_ANNOTATION,
-                                     new String[] {annotationId, documentId});
-
-    Answer answer = null;
-
-    if (log.isDebugEnabled()) {
-
-      log.debug("Executing query :" + query);
-    }
-
-    //Issue the query command
-    for (Object obj: itqlBean.executeQueryToList(query)) {
-
-      //Check for an answer
-      if (obj instanceof Answer) {
-
-        try {
-
-          //Check the number of rows returned
-          long solutionCount = ( (Answer) obj).getRowUpperBound();
-
-          if (log.isDebugEnabled()) {
-
-            log.debug("found answer :" + solutionCount);
-          }
-
-          //return the resultset if there are rows
-          if (solutionCount > 0) {
-
-            answer = (Answer) obj;
-          }
-        } catch (TuplesException ex) {
-
-          log.error("Error executing query :" + query, ex);
-        }
-      }
-    }
-
-    return answer;
-  }
-
-  /**
-   * Description of the Method
-   *
-   * @param documentId Description of Parameter
-   */
-  private void documentHasUpdated(String documentId) {
-
-    documentUpdates.put(documentId, new Long(System.currentTimeMillis()));
-
-    if (log.isDebugEnabled()) {
-
-      log.debug("DocumentId : " + documentId + " has been updated ");
-    }
-  }
-
-  /**
-   * Description of the Method
-   *
-   * @param documentId Description of Parameter
-   * @param emailAddress Description of Parameter
-   */
-  private void documentHasBeenRetrieved(String documentId, String emailAddress) {
-
-    lastChecked.put(documentId + emailAddress,
-                    new Long(System.currentTimeMillis()));
-
-    if (log.isDebugEnabled()) {
-
-      log.debug("DocumentId : " + documentId + " has been retrieved by " +
-                emailAddress);
-    }
-  }
-
-  /**
-   * Description of the Method
-   *
-   * @param documentId Description of Parameter
-   * @param emailAddress Description of Parameter
-   * @return Description of the Returned Value
-   */
-  private boolean hasDocumentUpdated(String documentId, String emailAddress) {
-
-    boolean updated = false;
-    long lastCheckedTime = 0;
-    long lastUpdatedTime = System.currentTimeMillis();
-
-    //Find out when the user performed the last retrieval for a document
-    if (lastChecked.containsKey(documentId + emailAddress)) {
-
-      lastCheckedTime = lastChecked.get(documentId + emailAddress).longValue();
-    }
-
-    //Find out the last updated time
-    if (documentUpdates.containsKey(documentId)) {
-
-      // has been updated
-      lastUpdatedTime = documentUpdates.get(documentId).longValue();
-    } else {
-
-      // No modification has occur for this document.
-      // ie. server has been started without any updates
-      documentHasUpdated(documentId);
-    }
-
-    //Is the last check time less than the last updated time?
-    updated = (lastCheckedTime < lastUpdatedTime);
-
-    if (log.isDebugEnabled()) {
-
-      log.debug("DocumentId : " + documentId +
-                " has been checked for updates " + "with result :" + updated +
-                " last checked :" + lastCheckedTime + " document updated :" +
-                lastUpdatedTime);
-    }
-
-    return updated;
-  }
-
-  /**
-   * Commence a new transaction for this session
-   *
-   * @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()) 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);
-      throw new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Unable to obtain a transaction for the Mulgara Collaborator <" + name + ">");
-    }
-  }
-
-  /**
-   * Commit the current transaction
-   *
-   * @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()) 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);
-      throw new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Unable to commit changes for the Mulgara Collaborator <" + name + ">");
-    }
-  }
-
-  /**
-   * Rollback the current transaction
-   *
-   * @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()) 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);
-
-      throw new SOAPException(Constants.FAULT_CODE_SERVER,
-          "Unable to rollback a transaction for the Mulgara Collaborator <" + name + ">");
-    }
-  }
-
-  /**
-   * Encode a literal string
-   *
-   * @param value String to encode
-   * @return A new encoded string 
-   */
-  private String encode(String value) {
-
-    return StringUtil.replaceStringWithString(value, "'", "\\'");
-  }
-
-  /**
-   * Decode a literal string
-   *
-   * @param value The string to decode
-   * @return A new decoded string
-   */
-  private String decode(String value) {
-
-    return StringUtil.replaceStringWithString(value, "\\'", "'");
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/Collaborator.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/Collaborator.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/Collaborator.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/Collaborator.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,1377 @@
+/*
+ * 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;
+
+// Java APIs
+import java.sql.*;
+import java.text.DateFormat;
+import java.util.*;
+
+// Mail api
+import javax.mail.*;
+import javax.mail.internet.*;
+
+// Third party packages
+import org.apache.log4j.*;
+import org.apache.soap.*;
+
+// JRDF
+import org.jrdf.graph.URIReference;
+
+// Locally written
+import org.mulgara.query.Answer;
+import org.mulgara.query.QueryException;
+import org.mulgara.query.TuplesException;
+import org.mulgara.query.Variable;
+import org.mulgara.query.rdf.LiteralImpl;
+import org.mulgara.util.StringUtil;
+
+/**
+ * Collaborator contains methods to store and manipulate annotations for the
+ * Collaborator Plug-in. All public methods are exposed as SOAP
+ * end-points
+ *
+ * @created 2002-04-08
+ *
+ * @author <a href="http://staff.PIsoftware.com/tate/">Tate Jones</a>
+ *
+ * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
+ *
+ * @copyright &copy; 2002-2003 <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 Collaborator {
+
+  /** 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 */
+  private static String SERVER_NAME = "server1";
+
+  /** 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. */
+  private static ItqlInterpreterBean itqlBean = null;
+
+  /** Default model to use */
+  private final static String MODEL = "collaborator";
+
+  /** Namespace for document */
+  private final static String NS = "http://mulgara.org/mulgara/Annotation#";
+
+  /** Email address predicate */
+  private final static String EMAIL_ADDRESS = NS + "emailAddress";
+
+  /** Nick name predicate */
+  private final static String NICK_NAME = NS + "nickName";
+
+  /** Text predicate */
+  private final static String TEXT = NS + "text";
+
+  /** documentId predicate */
+  private final static String DOCUMENT_ID = NS + "documentId";
+
+  /** annotationId predicate */
+  private final static String ANNOTATION_ID_PREFIX = NS + "annotationId";
+
+  /** annotationId predicate */
+  private final static String DATE = NS + "lastUpdate";
+
+  /** page number predicate */
+  private final static String PAGE_NUMBER = NS + "pageNumber";
+
+  /** x position predicate */
+  private final static String X_POSITION = NS + "xPosition";
+
+  /** y position predicate */
+  private final static String Y_POSITION = NS + "yPosition";
+
+  /** x anchor predicate */
+  private final static String X_ANCHOR = NS + "xAnchor";
+
+  /** y anchor predicate */
+  private final static String Y_ANCHOR = NS + "yAnchor";
+
+  /** height predicate */
+  private final static String HEIGHT = NS + "height";
+
+  /** width predicate */
+  private final static String WIDTH = NS + "width";
+
+  /** Access key prefix */
+  private final static String KEY_PREFIX = NS + "key";
+
+  /** 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 + ">;";
+
+  /** Delete the collaboration model */
+  private final static String DROP_MODEL = "drop <" + SERVER + MODEL + ">;";
+
+  /** Check for registration */
+  private final static String CHECK_REGISTRATION =
+      "select $key from <" + SERVER + MODEL + "> " + "where $key <" +
+      EMAIL_ADDRESS + "> <mailto:~01> ;";
+
+  /** 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 */
+  private final static String CHECK_ACCESS_KEY =
+      "select $emailaddress from <" + SERVER + MODEL + "> " + "where <" +
+      KEY_PREFIX + "~01> $emailaddress <mailto:~02> ;";
+
+  /** Create annotation */
+  private final static String INSERT_ANNOTATION =
+      "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + EMAIL_ADDRESS +
+      "> <mailto:~02> into <" + SERVER + MODEL + ">; " + "insert <" +
+      ANNOTATION_ID_PREFIX + "~01> <" + NICK_NAME + "> '~03' into <" + SERVER +
+      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + TEXT +
+      "> '~04' into <" + SERVER + MODEL + ">; " + "insert <" +
+      ANNOTATION_ID_PREFIX + "~01> <" + PAGE_NUMBER + "> '~05' into <" + SERVER +
+      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + X_POSITION +
+      "> '~06' into <" + SERVER + MODEL + ">; " + "insert <" +
+      ANNOTATION_ID_PREFIX + "~01> <" + Y_POSITION + "> '~07' into <" + SERVER +
+      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + X_ANCHOR +
+      "> '~08' into <" + SERVER + MODEL + ">; " + "insert <" +
+      ANNOTATION_ID_PREFIX + "~01> <" + Y_ANCHOR + "> '~09' into <" + SERVER +
+      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + HEIGHT +
+      "> '~10' into <" + SERVER + MODEL + ">; " + "insert <" +
+      ANNOTATION_ID_PREFIX + "~01> <" + WIDTH + "> '~11' into <" + SERVER +
+      MODEL + ">; " + "insert <" + ANNOTATION_ID_PREFIX + "~01> <" + DATE +
+      "> '~12' into <" + SERVER + MODEL + ">; " + "insert <" +
+      ANNOTATION_ID_PREFIX + "~01> <" + DOCUMENT_ID + "> '~13' into <" + SERVER +
+      MODEL + ">; ";
+
+  /** 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 */
+  private final static String DELETE_ANNOTATION_STATEMENT =
+      "delete <" + ANNOTATION_ID_PREFIX + "~01> <~02> ~03 from <" + SERVER +
+      MODEL + ">;";
+
+  /** Retrieve all annotations */
+  private final static String RETRIEVE_ANNOTATIONS =
+      "select $annotationId $emailaddress $nickname $text $pageno " +
+      "$x $y $xanchor $yanchor $height $width $lastupdated $documentid " +
+      "from <" + SERVER + MODEL + "> " + "where $annotationId <" + DOCUMENT_ID +
+      "> '~01' and " + "$annotationId <" + EMAIL_ADDRESS +
+      "> $emailaddress and " + "$annotationId <" + NICK_NAME +
+      "> $nickname and " + "$annotationId <" + TEXT + "> $text and " +
+      "$annotationId <" + PAGE_NUMBER + "> $pageno and " + "$annotationId <" +
+      X_POSITION + "> $x and " + "$annotationId <" + Y_POSITION + "> $y and " +
+      "$annotationId <" + X_ANCHOR + "> $xanchor and " + "$annotationId <" +
+      Y_ANCHOR + "> $yanchor and " + "$annotationId <" + HEIGHT +
+      "> $height and " + "$annotationId <" + WIDTH + "> $width and " +
+      "$annotationId <" + DATE + "> $lastupdated and " + "$annotationId <" +
+      DOCUMENT_ID + "> $documentid ;";
+
+  /** Method identifier used for transaction naming */
+  private static final String EXECUTE_COMMAND_TX = "executeCommand";
+
+  /** 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 */
+  DateFormat dateFormat = DateFormat.getInstance();
+
+  /** 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<String,Long> lastChecked = new HashMap<String,Long>();
+
+  /**
+   * The Collaborator will create the ITQL interpreter bean.
+   */
+  public Collaborator() {
+
+    if (itqlBean == null) {
+
+      itqlBean = new ItqlInterpreterBean();
+
+      //Has the server name been determined
+      if (SERVER.length() == 0) log.fatal("Unable to determine localhost name");
+
+      try {
+        initializeModel();
+      } catch (Exception ex) {
+        log.fatal("Unable to initialize collaboration model", ex);
+      }
+    }
+  }
+
+
+  /**
+   * Closes the underlying itql interpreter bean.
+   */
+  public void close() {
+    if (itqlBean != null) {
+      itqlBean.close();
+      itqlBean = null;
+    }
+  }
+
+  /**
+   * Send an email message via SMTP.
+   *
+   * @param from The From address.
+   * @param to The To address.
+   * @param subject The email subject
+   * @param content The email content
+   */
+  private static void sendEmail(String from, String to, String subject,
+                                String content) {
+
+    if (log.isDebugEnabled()) {
+
+      log.debug("sending email from :" + from + " to :" + to + eol +
+          "subject :" + subject + eol + "Content :" + content);
+    }
+
+    //Check for smtp server setting
+    Properties props = System.getProperties();
+
+    if ((props.get("mail.smtp.host") == null) ||
+        (((String) props.get("mail.smtp.host")).length() == 0)) {
+
+      log.warn("unable to send email from :" + from + " to :" + to + eol +
+          "subject :" + subject + eol + "Content :" + content +
+          " - SMTP server not configured");
+
+      return;
+    }
+
+    try {
+
+      // get the default Session
+      javax.mail.Session session =
+          javax.mail.Session.getDefaultInstance(props, null);
+
+      // Set up the to address
+      Address[] toAddress = InternetAddress.parse(to, false);
+
+      // create a message
+      Message message = new MimeMessage(session);
+
+      message.setFrom(new InternetAddress(from));
+
+      message.setSubject(subject);
+      message.setHeader("X-Mailer", "Collaborator Registration");
+      message.setSentDate(new java.util.Date());
+      message.setRecipients(Message.RecipientType.TO, toAddress);
+      message.setText(content);
+
+      // Send newMessage
+      Transport.send(message);
+    } catch (NoSuchProviderException nex) {
+
+      log.error("Cannot send email", nex);
+    } catch (AddressException ex) {
+
+      log.error("Cannot send email", ex);
+    } catch (MessagingException mex) {
+
+      log.error("Cannot send email", mex);
+    }
+  }
+
+  /**
+   * Retrieve a URL from the server based on a specific client request.
+   *
+   * The client will open a new web browser and read the contents of the URL.
+   * This will method will be used to display messages to user.
+   *
+   * @param emailAddress user performing the request
+   * @param key the current access
+   * @param requestType types of requests are:
+   *      <dl>
+   *      <dt>welcome</dt>    <dd>returns a URL for a welcome page</dd>
+   *      <dt>help</dt>       <dd>returns a URL for a help page</dd>
+   *      <dt>invalidkey</dt> <dd>returns a URL for an invalid key page</dd>
+   *      <dt>keyexpired</dt> <dd>returns a URL for an expired key page</dd>
+   *      <dt>invalidemailkey</dt>
+   *        <dd>returns a URL for an invalid email and key match</dd>
+   *      <dt>reports</dt>    <dd>returns a URL for a reports page</dd>
+   *      </dl>
+   * @return the URL to be viewed
+   * @throws SOAPException  Description of Exception
+   */
+  public String getURL(String emailAddress, String key, String requestType)
+    throws SOAPException {
+
+    return "";
+  }
+
+  /**
+   * Perform a registation of a new user. A successful registration will result
+   * in an email been sent containing an access key to initiate the plug-in for
+   * a set period. ?All details are recorded in the Mulgara database.
+   *
+   * @param emailAddress ?email address to send the access key to
+   * @param nickName ? the user name to be registered
+   * @return Description of the Returned Value
+   * @throws SOAPException excepted errors are :emailAddress and/or nickName
+   *      have not been supplied, invalid email address, email address has
+   *      already been registered, error sending email
+   */
+  public synchronized boolean register(String emailAddress, String nickName) throws
+      SOAPException {
+
+    boolean registered = false;
+
+    //Check supplied parameters
+    if ((emailAddress == null) ||
+        (nickName == null) ||
+        (emailAddress.length() == 0) ||
+        (nickName.length() == 0)) {
+
+      log.warn("Null paramaters supplied for email address or nickname");
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Email address and nick name must be supplied");
+    }
+
+    //TODO : validate email address
+    //Check for existing registration
+    if (executeCommand(CHECK_REGISTRATION, new String[] {emailAddress}, 0, false)) {
+
+      //new registration required
+      // TODO : create a better access key
+      String key = String.valueOf(System.currentTimeMillis());
+
+      //For testing purposes only!!! see unit tests
+      lastAccessKeyCreated = key;
+
+      //TODO : Calculate expiry date
+      registered = executeCommand(INSERT_REGISTRATION, new String[] {key, emailAddress, nickName},
+                              "Successfully inserted", true);
+
+      //Send an email with the registration key
+      if (registered) {
+        sendEmail("foo at localhost", emailAddress,
+                       "Collaborator Registration",
+                       "Welcome to Mulgara Collaborator. Your access key is " + key);
+      }
+    } else {
+
+      log.warn("Existing registration already exists for " + emailAddress);
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Your Email address has already been registered");
+    }
+
+    return registered;
+  }
+
+  /**
+   * Check for a valid access key for the plug-in. Confirms the access key is
+   * valid for the supplied email address and the access period has not been
+   * exceed. ?
+   *
+   * @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 ?
+   */
+  public boolean checkAccessKey(String key, String emailAddress) throws SOAPException {
+
+    boolean accessOk = false;
+
+    // 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");
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Email address and key name must be supplied");
+    }
+
+    //Check for the access key
+    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");
+      }
+
+      accessOk = true;
+    } else {
+      log.warn("Invaild access key :" + key + " for email address :" + emailAddress);
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+                            "Invaild access key :" + key + " for email address :" + emailAddress);
+    }
+
+    return accessOk;
+  }
+
+  /**
+   * Adds an annotation to a specified document.
+   *
+   * A successful addition will result in an unique annotation id returned.
+   * An annotation contains the following details.
+   *
+   * @param emailAddress  emailAddress user performing the request
+   * @param key           the current access key
+   * @param nickName      nickName the user adding the annotation
+   * @param documentId    documentId unique identifier for the document
+   * @param text          the annotation text
+   * @param pageNo        page number of the annotation
+   * @param xAnchor       x position of the annotation
+   * @param yAnchor       y position of the annotation
+   * @param x             visual x position of the annotation text box
+   * @param y             visual y position of the annotation text box
+   * @param height        visual height of the annotation text box
+   * @param width         visual width of the annotation text box
+   * @return returns a non blank annotationId
+   * @throws SOAPException excepted errors are:
+   *   <ul><li>key is invalid</li>
+   *       <li>key has expired</li>
+   *       <li>invalid parameters supplied</li></ul>
+   */
+  public synchronized String addAnnotation(String emailAddress,
+                                           String key,
+                                           String nickName,
+                                           String documentId,
+                                           String text,
+                                           String pageNo,
+                                           String xAnchor,
+                                           String yAnchor,
+                                           String x,
+                                           String y,
+                                           String height,
+                                           String width) throws SOAPException {
+
+    return addAnnotation(emailAddress, key, nickName, documentId, text,
+                         pageNo, xAnchor, yAnchor, x, y, height, width, true);
+  }
+
+  /**
+   * Remove an annotation from a specified document ?
+   *
+   * @param emailAddress email address of user performing the request
+   * @param key access key for the request email address
+   * @param documentId the document containing the annotation
+   * @param annotationId the annotation to be removed
+   * @return returns true if successful
+   * @throws SOAPException Exceptions are : emailAddress and key do not match,
+   *      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 {
+
+    return removeAnnotation(emailAddress, key, documentId, annotationId, true);
+  }
+
+  /**
+   * Edit an exisiting annotation ?
+   *
+   * @param emailAddress emailAddress user performing the request
+   * @param key the current access key
+   * @param nickName nickName the user adding the annotation
+   * @param documentId documentId unique identifier for the document
+   * @param annotationId Description of Parameter
+   * @param text the annotation text
+   * @param pageNo page number of the annotation
+   * @param xAnchor x position of the annotation
+   * @param yAnchor y position of the annotation
+   * @param x visual x position of the annotation text box
+   * @param y visual y position of the annotation text box
+   * @param height visual height of the annotation text box
+   * @param width visual width of the annotation text box
+   * @return returns a non blank annotationId
+   * @throws SOAPException excepted errors are : key is invaild, key has
+   *      expired, invalid parameters supplied ?
+   */
+  public synchronized String editAnnotation(String emailAddress, String key,
+                                            String nickName, String documentId,
+                                            String annotationId, String text,
+                                            String pageNo, String xAnchor,
+                                            String yAnchor, String x, String y,
+                                            String height, String width) throws
+      SOAPException {
+
+    boolean added = false;
+
+    // Check the the access key for this user.
+    // Will throw an exception if the access key is incorrect
+    checkAccessKey(key, emailAddress);
+
+    //Check parameters
+    if ( (documentId == null) ||
+        (documentId.length() == 0) ||
+        (annotationId == null) ||
+        (annotationId.length() == 0) ||
+        (pageNo == null) ||
+        (pageNo.length() == 0) ||
+        (xAnchor == null) ||
+        (xAnchor.length() == 0) ||
+        (yAnchor == null) ||
+        (yAnchor.length() == 0) ||
+        (x == null) ||
+        (x.length() == 0) ||
+        (y == null) ||
+        (y.length() == 0) ||
+        (height == null) ||
+        (height.length() == 0) ||
+        (width == null) ||
+        (width.length() == 0)) {
+
+      log.warn("Invalid paramaters supplied for annotation");
+
+      SOAPException se =
+          new SOAPException(Constants.FAULT_CODE_SERVER,
+                            "Invalid paramaters supplied for annotation");
+      throw se;
+    }
+
+    //Correct the text if null
+    if (text == null) {
+
+      text = "";
+    }
+
+    // Commence a new transaction for the removing and
+    // adding of a new annotation.
+    beginTransaction("editAnnotation");
+
+    try {
+
+      //Remove the annotation
+      if (removeAnnotation(emailAddress, key, documentId, annotationId, false)) {
+
+        //Add the modified annotation
+        annotationId =
+            addAnnotation(emailAddress, key, nickName, documentId, text, pageNo,
+                          xAnchor, yAnchor, x, y, height, width, false);
+
+        //Check the result
+        added = (annotationId.length() > 0);
+      }
+    } catch (SOAPException ex) {
+
+      //Rollback the transaction
+      rollback("editAnnotation");
+
+      // re-throw the exception
+      throw ex;
+    }
+
+    //Check for a new annotation
+    if (!added) {
+
+      //Rollback the transaction
+      rollback("editAnnotation");
+
+      log.warn("Unable to edit annotation documentId :" + documentId +
+               " annotationId :" + annotationId);
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+                            "Unable to edit annotation");
+    } else {
+
+      // Commit the changes
+      commit("editAnnotation");
+
+      // the flag the update document
+      documentHasUpdated(documentId);
+    }
+
+    return annotationId;
+  }
+
+  /**
+   * Retrieve all annotations for a specified docoument
+   *
+   * @param emailAddress emailAddress user performing the request
+   * @param key the current access key
+   * @param documentId unique identifier for the document
+   * @return Description of the Returned Value
+   * @throws SOAPException errors are : emailAddress and key do not match, key
+   *      is invalid, key has expired, invalid parameters supplied, invalid
+   *      documentId supplied
+   */
+  public synchronized String retrieveAnnotations(
+      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
+    checkAccessKey(key, emailAddress);
+
+    //Check parameters
+    if ((documentId == null) || (documentId.length() == 0)) {
+
+      log.warn("Invalid paramaters supplied for retrieving annotations");
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+          "Invalid paramaters supplied for retrieving annotations");
+    }
+
+    String results = "";
+
+    //Subsitute the parameter into the query
+    String query = StringUtil.substituteStrings(RETRIEVE_ANNOTATIONS, documentId);
+
+    if (log.isDebugEnabled()) log.debug("Executing query :" + query);
+
+    //Issue the query
+    try {
+      results = decode(itqlBean.executeQueryToString(query));
+    } catch (Exception ex) {
+
+      log.error("Unable to retrieve annotations for documentId :" + documentId, ex);
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to retrieve annotations: " + ex.getMessage(), ex);
+    }
+
+    // track the document retrieval
+    documentHasBeenRetrieved(documentId, emailAddress);
+
+    return results;
+  }
+
+  /**
+   * Check for annotation updates after a specified date and time.
+   *
+   * @param emailAddress emailAddress user performing the request
+   * @param key the current access key
+   * @param documentId unique identifier for the document
+   * @return return true if updates have been made
+   * @throws SOAPException errors are : emailAddress and key do not match, key
+   *      is invalid, key has expired, invalid parameters supplied, invalid
+   *      documentId supplied
+   */
+  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
+    checkAccessKey(key, emailAddress);
+
+    // Check parameters
+    if ((documentId == null) || (documentId.length() == 0)) {
+      log.warn("Invalid paramaters supplied for retrieving annotations");
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for retrieving annotations");
+    }
+
+    return hasDocumentUpdated(documentId, emailAddress);
+  }
+
+  /**
+   * 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
+   * @throws SQLException Unable to interate over the model details
+   * @throws SOAPException EXCEPTION TO DO
+   */
+  public synchronized boolean initializeModel() throws QueryException,
+      SQLException, SOAPException {
+
+    boolean initialized = false;
+
+    try {
+      // ignore string output
+      itqlBean.executeQueryToString(CHECK_MODEL);
+    } catch (Exception ex) {
+
+      ex.printStackTrace();
+    }
+
+    String model = null;
+
+    for (Object obj: itqlBean.executeQueryToList(CHECK_MODEL)) {
+
+      if (obj instanceof Answer) {
+
+        Answer answer = (Answer)obj;
+
+        try {
+          //reset cursor
+          answer.beforeFirst();
+
+          while (answer.next()) {
+
+            model = ((URIReference)answer.getObject(answer.getColumnIndex(new Variable("model")))).getURI().toString();
+
+            if (log.isDebugEnabled()) log.debug("Found model :" + model);
+
+            int pos = model.indexOf("#");
+
+            if (pos >= 0) {
+
+              if (log.isDebugEnabled()) log.debug("Testing model :" + model.substring(pos + 1));
+              initialized = (model.substring(pos + 1).equals(MODEL));
+            }
+          }
+        } catch (TuplesException e) {
+          throw new QueryException("Couldn't initialize model", e);
+        }
+      } else {
+
+        if (obj instanceof String) {
+
+          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);
+        }
+      }
+    }
+
+    if (initialized == false) {
+      // Model has not been initialized
+      initialized = createModel();
+    } else {
+      log.debug("Collaborator model already initialized at " + SERVER + MODEL);
+    }
+
+    return initialized;
+  }
+
+  /**
+   * Creates a new collaborator model
+   *
+   * @return returns true if successful
+   * @throws SOAPException Error creating the model on the server
+   */
+  public synchronized boolean createModel() throws SOAPException {
+
+    log.warn("creating model " + SERVER + MODEL);
+    return executeCommand(CREATE_MODEL, "Successfully created graph", false);
+  }
+
+  /**
+   * Drops a collaboration model
+   *
+   * @return returns true is sucessful
+   * @throws SOAPException EXCEPTION TO DO
+   */
+  public synchronized boolean dropModel() throws SOAPException {
+
+    log.warn("dropping model " + SERVER + MODEL);
+    return executeCommand(DROP_MODEL, "Successfully dropped graph", false);
+  }
+
+  /**
+   * Test method for SOAP calls
+   *
+   * @return a success message
+   */
+  public String test() {
+
+    return "test";
+  }
+
+  /**
+   * Remove an annotation from a specified document ?
+   *
+   * @param emailAddress email address of user performing the request
+   * @param key access key for the request email address
+   * @param documentId the document containing the annotation
+   * @param annotationId the annotation to be removed
+   * @param trans insert method into a transaction
+   * @return returns true if successful
+   * @throws SOAPException Exceptions are : emailAddress and key do not match,
+   *      key is invaild, key has expired, invalid parameters supplied,
+   *      annotation does not exist
+   */
+  private boolean removeAnnotation(String emailAddress, String key,
+                                   String documentId, String annotationId,
+                                   boolean trans) throws SOAPException {
+
+    boolean removed = false;
+
+    // Check the the access key for this user.
+    // Will throw an exception if the access key is incorrect
+    if (trans) checkAccessKey(key, emailAddress);
+
+    //Check parameters
+    if ((documentId == null) ||
+        (documentId.length() == 0) ||
+        (annotationId == null) ||
+        (annotationId.length() == 0)) {
+
+      log.warn("Invalid paramaters supplied for annotation removal");
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for annotation removal");
+    }
+
+    //Retrieve the annotation
+    Answer annotation = retrieveAnnotation(documentId, annotationId);
+
+    if (annotation != null) {
+
+      String predicate = null;
+      String object = null;
+
+      //Begin a transaction to remove the statements
+      if (trans) beginTransaction(REMOVE_ANNOTATION_TX);
+
+      try {
+
+        //Extract the predicate and object from the resultSet
+        annotation.beforeFirst();
+
+        //Iterate over the rows
+        while (annotation.next()) {
+
+          //grab the predicate
+          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 = "'" + encode(((LiteralImpl) annotation.getObject(objectIndex)).getLexicalForm()) + "'";
+          } else if (annotation.getObject(objectIndex) instanceof URIReference) {
+
+            object = "<" + ((URIReference)annotation.getObject(objectIndex)).getURI() + ">";
+          }
+
+          String[] removalParams = new String[] {annotationId, predicate, object};
+          
+          // delete the annotation statement
+          removed = executeCommand(DELETE_ANNOTATION_STATEMENT,removalParams, "Successfully", false);
+
+          if (!removed) {
+
+            log.warn("Unable to remove annotation statement documentId :" +
+                     documentId + " annotationId :" + annotationId +
+                     " predicate :" +
+                     predicate + " object :" + object);
+            throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to remove annotation");
+          } else {
+
+            // the flag the update document
+            documentHasUpdated(documentId);
+          }
+        }
+
+        // Commit the deletions
+        if (trans) commit(REMOVE_ANNOTATION_TX);
+
+      } catch (TuplesException ex) {
+        // Rollback the transaction
+        if (trans) rollback(REMOVE_ANNOTATION_TX);
+
+        log.error("Unable to locate annotation for removal documentId :" +
+                  documentId + " annotationId :" + annotationId, ex);
+
+        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);
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Unable to locate annotation for removal");
+    }
+
+    return removed;
+  }
+
+  /**
+   * Adds an annotation to a specified document.
+   *
+   * A successful addition will result in a unique annotation id returned.
+   * An annotation contains the following details:
+   *
+   * @param emailAddress emailAddress user performing the request
+   * @param key the current access key
+   * @param nickName nickName the user adding the annotation
+   * @param documentId documentId unique identifier for the document
+   * @param text the annotation text
+   * @param pageNo page number of the annotation
+   * @param xAnchor x position of the annotation
+   * @param yAnchor y position of the annotation
+   * @param x visual x position of the annotation text box
+   * @param y visual y position of the annotation text box
+   * @param height visual height of the annotation text box
+   * @param width visual width of the annotation text box
+   * @param trans will this method be contained in a transaction
+   * @return returns a non blank annotationId
+   * @throws SOAPException excepted errors are:
+   *   <ul>
+   *   <li>key is invalid</li>
+   *   <li>key has expired</li>
+   *   <li>invalid parameters supplied</li>
+   *   </ul>
+   */
+  private String addAnnotation(String emailAddress, String key,
+                               String nickName, String documentId, String text,
+                               String pageNo,
+                               String xAnchor, String yAnchor, String x,
+                               String y, String height,
+                               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) checkAccessKey(key, emailAddress);
+
+    // Check parameters
+    if ((documentId == null) ||
+        (documentId.length() == 0) ||
+        (pageNo == null) ||
+        (pageNo.length() == 0) ||
+        (xAnchor == null) ||
+        (xAnchor.length() == 0) ||
+        (yAnchor == null) ||
+        (yAnchor.length() == 0) ||
+        (x == null) ||
+        (x.length() == 0) ||
+        (y == null) ||
+        (y.length() == 0) ||
+        (height == null) ||
+        (height.length() == 0) ||
+        (width == null) ||
+        (width.length() == 0)) {
+
+      log.warn("Invalid paramaters supplied for annotation");
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER, "Invalid paramaters supplied for annotation");
+    }
+
+    // Correct the text if null
+    if (text == null) text = "";
+
+    // Create the supporting attributes
+    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+    String lastUpdated = dateFormat.format(cal.getTime());
+
+    // 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);
+    }
+
+    // Start a transaction for all the inserts
+    if (trans) beginTransaction(ADD_ANNOTATION_TX);
+
+    String[] annotationParams = new String[] {
+        annotationId, emailAddress, nickName, encode(text), pageNo,
+        xAnchor, yAnchor, x, y, height, width, lastUpdated, documentId
+    };
+
+    // Clear the annotationId if unsuccessful - handling transactions at this level
+    if (!executeCommand(INSERT_ANNOTATION, annotationParams, "Successfully inserted", false)) {
+
+      annotationId = "";
+
+      // Rollback the inserts
+      if (trans) rollback(ADD_ANNOTATION_TX);
+
+    } else {
+
+      // Commit the inserts
+      if (trans) commit(ADD_ANNOTATION_TX);
+
+      // the flag the update document
+      documentHasUpdated(documentId);
+    }
+
+    return annotationId;
+  }
+
+  /**
+   * Execute an iTQL query and checks for a specific response
+   *
+   * @param command iTQLQuery
+   * @param substituteArray Description of Parameter
+   * @param rows the expected rows to be returned
+   * @param trans Insert command within a transaction
+   * @return returns true if the expect result is found in the response
+   * @throws SOAPException EXCEPTION TO DO
+   */
+  private boolean executeCommand(String command, String[] substituteArray,
+                                 int rows, boolean trans) throws SOAPException {
+
+    return executeCommand(command, substituteArray, String.valueOf(rows), trans);
+  }
+
+  /**
+   * Execute an iTQL query and checks for a specific response
+   *
+   * @param command iTQLQuery
+   * @param substituteArray Description of Parameter
+   * @param expectedResult the expected result
+   * @param trans Insert command within a transaction
+   * @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 {
+
+    boolean successful = false;
+
+    //Perform any subsitutions
+    if (substituteArray != null) {
+      command = StringUtil.substituteStrings(command, substituteArray);
+    }
+
+    String message = null;
+
+    if (log.isDebugEnabled()) log.debug("Executing command :" + command);
+
+    // Commence a new transaction if required
+    if (trans) beginTransaction(EXECUTE_COMMAND_TX);
+
+    // Issue the itql command
+    for (Object obj: itqlBean.executeQueryToList(command)) {
+
+      // Is the result a message?
+      if (obj instanceof String) {
+
+        message = (String)obj;
+
+        if (log.isDebugEnabled()) log.debug("returned message :" + message);
+
+        // Check the outcome against the expect result
+        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 answer?
+      if (obj instanceof Answer) {
+
+        try {
+
+          // Check the number of rows returned
+          long solutionCount = ((Answer)obj).getRowUpperBound();
+
+          if (log.isDebugEnabled()) log.debug("found answer :" + solutionCount);
+
+          message = String.valueOf(solutionCount);
+
+          // Check the outcome against the expect result
+          successful = ((message != null) && (message.indexOf(expectedResult) >= 0));
+
+          // break if failure occurs
+          if (!successful) break;
+
+        } catch (TuplesException ex) {
+
+          log.error("Error executing command :" + command, ex);
+          // Rollback the changes
+          if (trans) rollback(EXECUTE_COMMAND_TX);
+          return false;
+        }
+      }
+    }
+
+    // Commit the changes whether successful or not
+    if (trans) commit(EXECUTE_COMMAND_TX);
+
+    if (log.isDebugEnabled()) {
+      log.debug("Command :" + command + "message :" + message + " result :" + successful);
+    }
+
+    return successful;
+  }
+
+  /**
+   * Execute iTQL command and checks for a specific response
+   *
+   * @param command iTQL command
+   * @param expectedResult expected result to be checked
+   * @param trans Insert command within a transaction
+   * @return returns the resultSet null means no rows were found
+   * @throws SOAPException EXCEPTION TO DO
+   */
+  private boolean executeCommand(String command, String expectedResult,
+                                 boolean trans) throws SOAPException {
+
+    return executeCommand(command, null, expectedResult, trans);
+  }
+
+  /**
+   * Retrieve all statements for a specific annotationId
+   *
+   * @param documentId unique documentId
+   * @param annotationId AnnotationId for a document
+   * @return Return a resultSet null for no rows
+   */
+  private Answer retrieveAnnotation(String documentId, String annotationId) {
+
+    //Subsitute the parameter into the query
+    String query =
+        StringUtil.substituteStrings(RETRIEVE_ANNOTATION,
+                                     new String[] {annotationId, documentId});
+
+    Answer answer = null;
+
+    if (log.isDebugEnabled()) {
+
+      log.debug("Executing query :" + query);
+    }
+
+    //Issue the query command
+    for (Object obj: itqlBean.executeQueryToList(query)) {
+
+      //Check for an answer
+      if (obj instanceof Answer) {
+
+        try {
+
+          //Check the number of rows returned
+          long solutionCount = ( (Answer) obj).getRowUpperBound();
+
+          if (log.isDebugEnabled()) {
+
+            log.debug("found answer :" + solutionCount);
+          }
+
+          //return the resultset if there are rows
+          if (solutionCount > 0) {
+
+            answer = (Answer) obj;
+          }
+        } catch (TuplesException ex) {
+
+          log.error("Error executing query :" + query, ex);
+        }
+      }
+    }
+
+    return answer;
+  }
+
+  /**
+   * Description of the Method
+   *
+   * @param documentId Description of Parameter
+   */
+  private void documentHasUpdated(String documentId) {
+
+    documentUpdates.put(documentId, new Long(System.currentTimeMillis()));
+
+    if (log.isDebugEnabled()) {
+
+      log.debug("DocumentId : " + documentId + " has been updated ");
+    }
+  }
+
+  /**
+   * Description of the Method
+   *
+   * @param documentId Description of Parameter
+   * @param emailAddress Description of Parameter
+   */
+  private void documentHasBeenRetrieved(String documentId, String emailAddress) {
+
+    lastChecked.put(documentId + emailAddress,
+                    new Long(System.currentTimeMillis()));
+
+    if (log.isDebugEnabled()) {
+
+      log.debug("DocumentId : " + documentId + " has been retrieved by " +
+                emailAddress);
+    }
+  }
+
+  /**
+   * Description of the Method
+   *
+   * @param documentId Description of Parameter
+   * @param emailAddress Description of Parameter
+   * @return Description of the Returned Value
+   */
+  private boolean hasDocumentUpdated(String documentId, String emailAddress) {
+
+    boolean updated = false;
+    long lastCheckedTime = 0;
+    long lastUpdatedTime = System.currentTimeMillis();
+
+    //Find out when the user performed the last retrieval for a document
+    if (lastChecked.containsKey(documentId + emailAddress)) {
+
+      lastCheckedTime = lastChecked.get(documentId + emailAddress).longValue();
+    }
+
+    //Find out the last updated time
+    if (documentUpdates.containsKey(documentId)) {
+
+      // has been updated
+      lastUpdatedTime = documentUpdates.get(documentId).longValue();
+    } else {
+
+      // No modification has occur for this document.
+      // ie. server has been started without any updates
+      documentHasUpdated(documentId);
+    }
+
+    //Is the last check time less than the last updated time?
+    updated = (lastCheckedTime < lastUpdatedTime);
+
+    if (log.isDebugEnabled()) {
+
+      log.debug("DocumentId : " + documentId +
+                " has been checked for updates " + "with result :" + updated +
+                " last checked :" + lastCheckedTime + " document updated :" +
+                lastUpdatedTime);
+    }
+
+    return updated;
+  }
+
+  /**
+   * Commence a new transaction for this session
+   *
+   * @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()) 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);
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+          "Unable to obtain a transaction for the Mulgara Collaborator <" + name + ">");
+    }
+  }
+
+  /**
+   * Commit the current transaction
+   *
+   * @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()) 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);
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+          "Unable to commit changes for the Mulgara Collaborator <" + name + ">");
+    }
+  }
+
+  /**
+   * Rollback the current transaction
+   *
+   * @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()) 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);
+
+      throw new SOAPException(Constants.FAULT_CODE_SERVER,
+          "Unable to rollback a transaction for the Mulgara Collaborator <" + name + ">");
+    }
+  }
+
+  /**
+   * Encode a literal string
+   *
+   * @param value String to encode
+   * @return A new encoded string 
+   */
+  private String encode(String value) {
+
+    return StringUtil.replaceStringWithString(value, "'", "\\'");
+  }
+
+  /**
+   * Decode a literal string
+   *
+   * @param value The string to decode
+   * @return A new decoded string
+   */
+  private String decode(String value) {
+
+    return StringUtil.replaceStringWithString(value, "\\'", "'");
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,399 +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
-// Java 2 standard packages
-// Third party packages
-import java.io.IOException;
-
-import org.apache.log4j.Logger;
-import org.apache.soap.SOAPException;
-
-/**
- * Test cases for Collaborator.
- *
- * @author Tate Jones
- *
- * @created 2002-04-09
- *
- * @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;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 CollaboratorUnitTest extends TestCase {
-
-  /** Logger. */
-  @SuppressWarnings("unused")
-  private final static Logger logger = Logger.getLogger(CollaboratorUnitTest.class);
-
-  /**
-   * a flag to indicate if the collorator requires closing
-   *
-   * NOTE : retrieveAnnotationsTest toggles this flag
-   */
-  private boolean closeCollaborator = false;
-
-  /** Collaborator to be tested; */
-  Collaborator collaborator = null;
-
-  /**
-   * Create the testing class
-   *
-   * @param name The name of the test.
-   */
-  public CollaboratorUnitTest(String name) {
-    super(name);
-  }
-
-  /**
-   * Hook for test runner to obtain a test suite from.
-   *
-   * @return The test suite to run.
-   */
-  public static Test suite() {
-
-    TestSuite suite = new TestSuite();
-
-    suite.addTest(new CollaboratorUnitTest("initializeModelTest"));
-    suite.addTest(new CollaboratorUnitTest("modelTests"));
-    suite.addTest(new CollaboratorUnitTest("registrationTest"));
-    suite.addTest(new CollaboratorUnitTest("checkAccessKeyTest"));
-    suite.addTest(new CollaboratorUnitTest("addingAnnotationTest"));
-    suite.addTest(new CollaboratorUnitTest("removingAnnotationTest"));
-    suite.addTest(new CollaboratorUnitTest("editAnnotationTest"));
-    suite.addTest(new CollaboratorUnitTest("retrieveAnnotationsTest"));
-
-    return suite;
-  }
-
-  /**
-   * Default test runner.
-   *
-   * @param args The command line arguments
-   */
-  public static void main(String[] args) {
-
-    junit.textui.TestRunner.run(suite());
-  }
-
-  /**
-   * Setup for testing
-   *
-   * @throws IOException Description of Exception
-   */
-  public void setUp() throws IOException {
-
-    //Construct the collaborator();
-    collaborator = new Collaborator();
-  }
-
-  /**
-   * Tear down on completion
-   *
-   * @throws IOException Description of Exception
-   */
-  public void tearDown() throws IOException {
-    if (closeCollaborator) {
-      collaborator.close();
-    }
-  }
-
-  /**
-   * Test the initialization of the model
-   *
-   * @throws Exception Test fails
-   */
-  public void initializeModelTest() throws Exception {
-
-    assertTrue("Failed to initialize collaborator model", collaborator.initializeModel());
-  }
-
-  /**
-   * Test the creation and dropping of the model
-   *
-   */
-  public void modelTests() {
-
-    try {
-
-      assertTrue("Failed to drop collaborator model", collaborator.dropModel());
-
-      assertTrue("Expected collaborator model to be droped", collaborator.dropModel() == false);
-
-      assertTrue("Failed to create collaborator model", collaborator.createModel());
-    } catch (SOAPException ex) {
-      ex.printStackTrace();
-      fail("Model tests failed " + ex.getMessage());
-    }
-  }
-
-  /**
-   * Test the registration process
-   */
-  public void registrationTest() {
-
-    try {
-
-      assertTrue("Register user", collaborator.register("xyz at company.com", "Joe Brown"));
-    } catch (SOAPException ex) {
-      ex.printStackTrace();
-      fail("Registration test failed " + ex.getMessage());
-    }
-
-    try {
-      collaborator.register("xyz at company.com", "Alex Mole");
-      fail("Failed to detect duplicate registered user");
-    } catch (SOAPException ex) {
-      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");
-      fail("Failed to detect empty email address");
-    } catch (SOAPException ex) {
-      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"));
-    }
-  }
-
-  /**
-   * Check for valid access key
-   */
-  public void checkAccessKeyTest() {
-
-    try {
-
-      assertTrue("Unable to register user", collaborator.register("guest at mulgara.org", "Guest User"));
-
-      assertTrue("Expected to find registered user with key :" +
-          collaborator.lastAccessKeyCreated +
-          " email address : guest at mulgara.org",
-          collaborator.checkAccessKey(collaborator.lastAccessKeyCreated,
-          "guest at mulgara.org"));
-    } catch (SOAPException ex) {
-      ex.printStackTrace();
-      fail("Not expecting exception on checking access key " + ex.getMessage());
-    }
-
-    try {
-      collaborator.checkAccessKey("12345", "guest at mulgara.org");
-      fail("Failed to detect invalid access key");
-    } catch (SOAPException ex) {
-      assertTrue("Failed to get the expected message (Invaild access key)",
-          ex.getMessage().indexOf("Invaild access key") >= 0);
-    }
-  }
-
-  /**
-   * Test adding annotations
-   */
-  public void addingAnnotationTest() {
-
-    //Add a successful annotation
-    try {
-      assertTrue("Unable to register user", collaborator.register("guest2 at mulgara.org", "Guest User 2"));
-
-      String annotationId =
-          collaborator.addAnnotation("guest2 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "Guest User 2", "1234567890",
-          "This is a test annotation", "1", "10", "11", "100", "101", "50",
-          "50");
-
-      assertTrue("Unable to add annotation", (annotationId != null) && (annotationId.length() > 0));
-    } catch (SOAPException ex) {
-      ex.printStackTrace();
-      fail("Failed to add annotation");
-    }
-
-    // Add an invalid annotation - incorrect key
-    try {
-      collaborator.addAnnotation("guest2 at mulgara.org", "badkey",
-          "Guest User 2", "1234567890", "This is a test annotation", "1", "10",
-          "11", "100", "101", "50", "50");
-
-      fail("Expected bad access key error");
-    } catch (SOAPException ex) {
-      assertTrue("Failed to get the expected message (Invaild access key)",
-          ex.getMessage().indexOf("Invaild access key") >= 0);
-    }
-
-    // Add an invalid annotation - empty parameters
-    try {
-      collaborator.addAnnotation("guest2 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "Guest User 2", "1234567890",
-          "This is a another annotation test", "", "", "11", "100", "101",
-          "50", "50");
-
-      fail("Expected bad parameters supplied");
-    } catch (SOAPException ex) {
-      assertTrue("Failed to get the expected message (Invalid paramaters supplied for annotation)",
-          ex.getMessage().indexOf("Invalid paramaters supplied for annotation") >= 0);
-    }
-  }
-
-  /**
-   * Test removing annotations
-   */
-  public void removingAnnotationTest() {
-
-    String annotationId = null;
-
-    //Add and remove an annotation
-    try {
-      assertTrue("Unable to register user", collaborator.register("guest3 at mulgara.org", "Guest User 3"));
-
-      annotationId =
-          collaborator.addAnnotation("guest3 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "Guest User 3", "1234567890",
-          "This is a test annotation", "1", "10", "11", "100", "101", "50",
-          "50");
-
-      assertTrue("Unable to add annotation", (annotationId != null) && (annotationId.length() > 0));
-
-      assertTrue("Unable to remove annotation",
-          collaborator.removeAnnotation("guest3 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "1234567890", annotationId));
-    } catch (SOAPException ex) {
-      ex.printStackTrace();
-      fail("Failed to add/remove annotation");
-    }
-
-    // Test removing an annotation that does not exist
-    try {
-      assertTrue("Unable to remove annotation",
-          collaborator.removeAnnotation("guest3 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "1234567890", annotationId));
-      fail("Expected not to be a successful removal");
-    } catch (SOAPException ex) {
-      assertTrue(
-          "Failed to get the expected message (Unable to locate annotation for removal)",
-          ex.getMessage().indexOf("Unable to locate annotation for removal") >= 0);
-    }
-  }
-
-  /**
-   * Test editing annotations
-   */
-  public void editAnnotationTest() {
-
-    String annotationId = null;
-
-    //Add and remove an annotation
-    try {
-      assertTrue("Unable to register user", collaborator.register("guest4 at mulgara.org", "Guest User 4"));
-
-      annotationId =
-          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");
-
-      assertTrue("Unable to add annotation for editing test", (annotationId != null) && (annotationId.length() > 0));
-
-      annotationId =
-          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");
-
-      assertTrue("Unable to edit annotation", annotationId != null);
-    } catch (SOAPException ex) {
-      ex.printStackTrace();
-      fail("Failed to add/edit annotation");
-    }
-  }
-
-  /**
-   * Test retrieving annotations
-   */
-  public void retrieveAnnotationsTest() {
-
-    String annotationId = null;
-
-    //Add and remove an annotation
-    try {
-
-      assertTrue("Unable to register user",
-          collaborator.register("guest5 at mulgara.org", "Guest User 5"));
-
-      assertTrue("Expect document to be updated for retrieval",
-          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "newdocumentId"));
-
-      annotationId =
-          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 mulgara.org",
-          collaborator.lastAccessKeyCreated, "Guest User 5", "newdocumentId",
-          "Annotation text two", "2", "20", "22", "200", "202", "52", "52");
-
-      assertTrue("Unable to add annotation for retreving test",
-          (annotationId != null) && (annotationId.length() > 0));
-
-      assertTrue("Expect document to be updated for retrieval",
-          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "newdocumentId"));
-
-      String results =
-          collaborator.retrieveAnnotations("guest5 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "newdocumentId");
-
-      assertTrue("Unable to retrieve annotation",
-          (results != null) && (results.length() > 0) &&
-          (results.indexOf("newdocumentId") >= 0));
-
-      assertTrue("Expect document not to be updated for retrieval",
-          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
-          collaborator.lastAccessKeyCreated, "newdocumentId") == false);
-    } catch (SOAPException ex) {
-      ex.printStackTrace();
-      fail("Failed to add/retrieve annotation");
-    } finally {
-      // force the teardown to close the collaborator
-      closeCollaborator = true;
-    }
-
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CollaboratorUnitTest.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,399 @@
+/*
+ * 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
+// Java 2 standard packages
+// Third party packages
+import java.io.IOException;
+
+import org.apache.log4j.Logger;
+import org.apache.soap.SOAPException;
+
+/**
+ * Test cases for Collaborator.
+ *
+ * @author Tate Jones
+ *
+ * @created 2002-04-09
+ *
+ * @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;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 CollaboratorUnitTest extends TestCase {
+
+  /** Logger. */
+  @SuppressWarnings("unused")
+  private final static Logger logger = Logger.getLogger(CollaboratorUnitTest.class);
+
+  /**
+   * a flag to indicate if the collorator requires closing
+   *
+   * NOTE : retrieveAnnotationsTest toggles this flag
+   */
+  private boolean closeCollaborator = false;
+
+  /** Collaborator to be tested; */
+  Collaborator collaborator = null;
+
+  /**
+   * Create the testing class
+   *
+   * @param name The name of the test.
+   */
+  public CollaboratorUnitTest(String name) {
+    super(name);
+  }
+
+  /**
+   * Hook for test runner to obtain a test suite from.
+   *
+   * @return The test suite to run.
+   */
+  public static Test suite() {
+
+    TestSuite suite = new TestSuite();
+
+    suite.addTest(new CollaboratorUnitTest("initializeModelTest"));
+    suite.addTest(new CollaboratorUnitTest("modelTests"));
+    suite.addTest(new CollaboratorUnitTest("registrationTest"));
+    suite.addTest(new CollaboratorUnitTest("checkAccessKeyTest"));
+    suite.addTest(new CollaboratorUnitTest("addingAnnotationTest"));
+    suite.addTest(new CollaboratorUnitTest("removingAnnotationTest"));
+    suite.addTest(new CollaboratorUnitTest("editAnnotationTest"));
+    suite.addTest(new CollaboratorUnitTest("retrieveAnnotationsTest"));
+
+    return suite;
+  }
+
+  /**
+   * Default test runner.
+   *
+   * @param args The command line arguments
+   */
+  public static void main(String[] args) {
+
+    junit.textui.TestRunner.run(suite());
+  }
+
+  /**
+   * Setup for testing
+   *
+   * @throws IOException Description of Exception
+   */
+  public void setUp() throws IOException {
+
+    //Construct the collaborator();
+    collaborator = new Collaborator();
+  }
+
+  /**
+   * Tear down on completion
+   *
+   * @throws IOException Description of Exception
+   */
+  public void tearDown() throws IOException {
+    if (closeCollaborator) {
+      collaborator.close();
+    }
+  }
+
+  /**
+   * Test the initialization of the model
+   *
+   * @throws Exception Test fails
+   */
+  public void initializeModelTest() throws Exception {
+
+    assertTrue("Failed to initialize collaborator model", collaborator.initializeModel());
+  }
+
+  /**
+   * Test the creation and dropping of the model
+   *
+   */
+  public void modelTests() {
+
+    try {
+
+      assertTrue("Failed to drop collaborator model", collaborator.dropModel());
+
+      assertTrue("Expected collaborator model to be droped", collaborator.dropModel() == false);
+
+      assertTrue("Failed to create collaborator model", collaborator.createModel());
+    } catch (SOAPException ex) {
+      ex.printStackTrace();
+      fail("Model tests failed " + ex.getMessage());
+    }
+  }
+
+  /**
+   * Test the registration process
+   */
+  public void registrationTest() {
+
+    try {
+
+      assertTrue("Register user", collaborator.register("xyz at company.com", "Joe Brown"));
+    } catch (SOAPException ex) {
+      ex.printStackTrace();
+      fail("Registration test failed " + ex.getMessage());
+    }
+
+    try {
+      collaborator.register("xyz at company.com", "Alex Mole");
+      fail("Failed to detect duplicate registered user");
+    } catch (SOAPException ex) {
+      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");
+      fail("Failed to detect empty email address");
+    } catch (SOAPException ex) {
+      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"));
+    }
+  }
+
+  /**
+   * Check for valid access key
+   */
+  public void checkAccessKeyTest() {
+
+    try {
+
+      assertTrue("Unable to register user", collaborator.register("guest at mulgara.org", "Guest User"));
+
+      assertTrue("Expected to find registered user with key :" +
+          collaborator.lastAccessKeyCreated +
+          " email address : guest at mulgara.org",
+          collaborator.checkAccessKey(collaborator.lastAccessKeyCreated,
+          "guest at mulgara.org"));
+    } catch (SOAPException ex) {
+      ex.printStackTrace();
+      fail("Not expecting exception on checking access key " + ex.getMessage());
+    }
+
+    try {
+      collaborator.checkAccessKey("12345", "guest at mulgara.org");
+      fail("Failed to detect invalid access key");
+    } catch (SOAPException ex) {
+      assertTrue("Failed to get the expected message (Invaild access key)",
+          ex.getMessage().indexOf("Invaild access key") >= 0);
+    }
+  }
+
+  /**
+   * Test adding annotations
+   */
+  public void addingAnnotationTest() {
+
+    //Add a successful annotation
+    try {
+      assertTrue("Unable to register user", collaborator.register("guest2 at mulgara.org", "Guest User 2"));
+
+      String annotationId =
+          collaborator.addAnnotation("guest2 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "Guest User 2", "1234567890",
+          "This is a test annotation", "1", "10", "11", "100", "101", "50",
+          "50");
+
+      assertTrue("Unable to add annotation", (annotationId != null) && (annotationId.length() > 0));
+    } catch (SOAPException ex) {
+      ex.printStackTrace();
+      fail("Failed to add annotation");
+    }
+
+    // Add an invalid annotation - incorrect key
+    try {
+      collaborator.addAnnotation("guest2 at mulgara.org", "badkey",
+          "Guest User 2", "1234567890", "This is a test annotation", "1", "10",
+          "11", "100", "101", "50", "50");
+
+      fail("Expected bad access key error");
+    } catch (SOAPException ex) {
+      assertTrue("Failed to get the expected message (Invaild access key)",
+          ex.getMessage().indexOf("Invaild access key") >= 0);
+    }
+
+    // Add an invalid annotation - empty parameters
+    try {
+      collaborator.addAnnotation("guest2 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "Guest User 2", "1234567890",
+          "This is a another annotation test", "", "", "11", "100", "101",
+          "50", "50");
+
+      fail("Expected bad parameters supplied");
+    } catch (SOAPException ex) {
+      assertTrue("Failed to get the expected message (Invalid paramaters supplied for annotation)",
+          ex.getMessage().indexOf("Invalid paramaters supplied for annotation") >= 0);
+    }
+  }
+
+  /**
+   * Test removing annotations
+   */
+  public void removingAnnotationTest() {
+
+    String annotationId = null;
+
+    //Add and remove an annotation
+    try {
+      assertTrue("Unable to register user", collaborator.register("guest3 at mulgara.org", "Guest User 3"));
+
+      annotationId =
+          collaborator.addAnnotation("guest3 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "Guest User 3", "1234567890",
+          "This is a test annotation", "1", "10", "11", "100", "101", "50",
+          "50");
+
+      assertTrue("Unable to add annotation", (annotationId != null) && (annotationId.length() > 0));
+
+      assertTrue("Unable to remove annotation",
+          collaborator.removeAnnotation("guest3 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "1234567890", annotationId));
+    } catch (SOAPException ex) {
+      ex.printStackTrace();
+      fail("Failed to add/remove annotation");
+    }
+
+    // Test removing an annotation that does not exist
+    try {
+      assertTrue("Unable to remove annotation",
+          collaborator.removeAnnotation("guest3 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "1234567890", annotationId));
+      fail("Expected not to be a successful removal");
+    } catch (SOAPException ex) {
+      assertTrue(
+          "Failed to get the expected message (Unable to locate annotation for removal)",
+          ex.getMessage().indexOf("Unable to locate annotation for removal") >= 0);
+    }
+  }
+
+  /**
+   * Test editing annotations
+   */
+  public void editAnnotationTest() {
+
+    String annotationId = null;
+
+    //Add and remove an annotation
+    try {
+      assertTrue("Unable to register user", collaborator.register("guest4 at mulgara.org", "Guest User 4"));
+
+      annotationId =
+          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");
+
+      assertTrue("Unable to add annotation for editing test", (annotationId != null) && (annotationId.length() > 0));
+
+      annotationId =
+          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");
+
+      assertTrue("Unable to edit annotation", annotationId != null);
+    } catch (SOAPException ex) {
+      ex.printStackTrace();
+      fail("Failed to add/edit annotation");
+    }
+  }
+
+  /**
+   * Test retrieving annotations
+   */
+  public void retrieveAnnotationsTest() {
+
+    String annotationId = null;
+
+    //Add and remove an annotation
+    try {
+
+      assertTrue("Unable to register user",
+          collaborator.register("guest5 at mulgara.org", "Guest User 5"));
+
+      assertTrue("Expect document to be updated for retrieval",
+          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "newdocumentId"));
+
+      annotationId =
+          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 mulgara.org",
+          collaborator.lastAccessKeyCreated, "Guest User 5", "newdocumentId",
+          "Annotation text two", "2", "20", "22", "200", "202", "52", "52");
+
+      assertTrue("Unable to add annotation for retreving test",
+          (annotationId != null) && (annotationId.length() > 0));
+
+      assertTrue("Expect document to be updated for retrieval",
+          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "newdocumentId"));
+
+      String results =
+          collaborator.retrieveAnnotations("guest5 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "newdocumentId");
+
+      assertTrue("Unable to retrieve annotation",
+          (results != null) && (results.length() > 0) &&
+          (results.indexOf("newdocumentId") >= 0));
+
+      assertTrue("Expect document not to be updated for retrieval",
+          collaborator.checkAnnotationUpdates("guest5 at mulgara.org",
+          collaborator.lastAccessKeyCreated, "newdocumentId") == false);
+    } catch (SOAPException ex) {
+      ex.printStackTrace();
+      fail("Failed to add/retrieve annotation");
+    } finally {
+      // force the teardown to close the collaborator
+      closeCollaborator = true;
+    }
+
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,31 +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.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);
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CommandSplitter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -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);
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,118 +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
- * Northrop Grumman Corporation. All Rights Reserved.
- *
- * This file is an original work and contains no Original Code.  It was
- * developed by Netymon Pty Ltd under contract to the Australian 
- * Commonwealth Government, Defense Science and Technology Organisation
- * under contract #4500507038 and is contributed back to the Kowari/Mulgara
- * Project as per clauses 4.1.3 and 4.1.4 of the above contract.
- *
- * Contributor(s): N/A.
- *
- * Copyright:
- *   The copyright on this file is held by:
- *     The Australian Commonwealth Government
- *     Department of Defense
- *   Developed by Netymon Pty Ltd
- * Copyright (C) 2006
- * The Australian Commonwealth Government
- * Department of Defense
- *
- * [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.util.ArrayList;
-import java.util.List;
-
-// Third party packages
-import org.apache.log4j.Logger; 
-
-// Generated packages
-import org.mulgara.itql.analysis.*;
-import org.mulgara.itql.node.*;
-
-/**
- * Create a list of predicates and their associated object lists from a compound constraint.
- *
- * @created 2006-04-07
- *
- * @author Andrae Muys
- *
- * @company <a href="mailto:mail at netymon.com">Netymon Pty Ltd</a>
- *
- * @copyright &copy;2006 Australian Commonwealth Government.
- *      All rights reserved.
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class CompoundPredListBuilder extends AnalysisAdapter {
-
-  private final static Logger logger = Logger.getLogger(CompoundPredListBuilder.class.getName());
-
-  private List<CompoundPredicate> predLists;
-
-  /**
-   * Constructor.
-   */
-  public CompoundPredListBuilder() {
-    predLists = new ArrayList<CompoundPredicate>();
-  }
-
-  public List<CompoundPredicate> getPredLists() {
-    return predLists;
-  }
-
-  /**
-   * Used to accumulate predicate lists.
-   */
-  private void addPredicateList(CompoundPredicate plist) {
-    predLists.add(plist);
-  }
-
-  public void caseAColonExistsExpression(AColonExistsExpression 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);
-    expr.getExistsPterm().apply(this);
-  }
-
-  public void caseAPtermExistsPterm(APtermExistsPterm rawTerm) {
-    if (logger.isDebugEnabled()) logger.debug("Found an Existential Predicate Term: " + rawTerm);
-
-    ObjectListBuilder builder = new ObjectListBuilder();
-    rawTerm.getExistsOterm().apply(builder);
-
-    this.addPredicateList(new CompoundPredicate(rawTerm.getPredicate(), builder.getObjectList()));
-  }
-
-  public void defaultCase(Node node) {
-    if (logger.isDebugEnabled()) logger.debug("Found node in pred builder: " + node + "::" + node.getClass());
-  }
-}
-

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredListBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,118 @@
+/*
+ * 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
+ * Northrop Grumman Corporation. All Rights Reserved.
+ *
+ * This file is an original work and contains no Original Code.  It was
+ * developed by Netymon Pty Ltd under contract to the Australian 
+ * Commonwealth Government, Defense Science and Technology Organisation
+ * under contract #4500507038 and is contributed back to the Kowari/Mulgara
+ * Project as per clauses 4.1.3 and 4.1.4 of the above contract.
+ *
+ * Contributor(s): N/A.
+ *
+ * Copyright:
+ *   The copyright on this file is held by:
+ *     The Australian Commonwealth Government
+ *     Department of Defense
+ *   Developed by Netymon Pty Ltd
+ * Copyright (C) 2006
+ * The Australian Commonwealth Government
+ * Department of Defense
+ *
+ * [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.util.ArrayList;
+import java.util.List;
+
+// Third party packages
+import org.apache.log4j.Logger; 
+
+// Generated packages
+import org.mulgara.itql.analysis.*;
+import org.mulgara.itql.node.*;
+
+/**
+ * Create a list of predicates and their associated object lists from a compound constraint.
+ *
+ * @created 2006-04-07
+ *
+ * @author Andrae Muys
+ *
+ * @company <a href="mailto:mail at netymon.com">Netymon Pty Ltd</a>
+ *
+ * @copyright &copy;2006 Australian Commonwealth Government.
+ *      All rights reserved.
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class CompoundPredListBuilder extends AnalysisAdapter {
+
+  private final static Logger logger = Logger.getLogger(CompoundPredListBuilder.class.getName());
+
+  private List<CompoundPredicate> predLists;
+
+  /**
+   * Constructor.
+   */
+  public CompoundPredListBuilder() {
+    predLists = new ArrayList<CompoundPredicate>();
+  }
+
+  public List<CompoundPredicate> getPredLists() {
+    return predLists;
+  }
+
+  /**
+   * Used to accumulate predicate lists.
+   */
+  private void addPredicateList(CompoundPredicate plist) {
+    predLists.add(plist);
+  }
+
+  public void caseAColonExistsExpression(AColonExistsExpression 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);
+    expr.getExistsPterm().apply(this);
+  }
+
+  public void caseAPtermExistsPterm(APtermExistsPterm rawTerm) {
+    if (logger.isDebugEnabled()) logger.debug("Found an Existential Predicate Term: " + rawTerm);
+
+    ObjectListBuilder builder = new ObjectListBuilder();
+    rawTerm.getExistsOterm().apply(builder);
+
+    this.addPredicateList(new CompoundPredicate(rawTerm.getPredicate(), builder.getObjectList()));
+  }
+
+  public void defaultCase(Node node) {
+    if (logger.isDebugEnabled()) logger.debug("Found node in pred builder: " + node + "::" + node.getClass());
+  }
+}
+

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,92 +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
- * Northrop Grumman Corporation. All Rights Reserved.
- *
- * This file is an original work and contains no Original Code.  It was
- * developed by Netymon Pty Ltd under contract to the Australian 
- * Commonwealth Government, Defense Science and Technology Organisation
- * under contract #4500507038 and is contributed back to the Kowari/Mulgara
- * Project as per clauses 4.1.3 and 4.1.4 of the above contract.
- *
- * Contributor(s): N/A.
- *
- * Copyright:
- *   The copyright on this file is held by:
- *     The Australian Commonwealth Government
- *     Department of Defense
- *   Developed by Netymon Pty Ltd
- * Copyright (C) 2006
- * The Australian Commonwealth Government
- * Department of Defense
- *
- * [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.util.List;
-
-// Third party packages
-// import org.apache.log4j.Logger; 
-
-// Generated packages
-import org.mulgara.itql.node.*;
-
-/**
- * A predicate element and a list of associated objects.  A list of these will be
- * associated with a given subject element in a compound constraint.
- *
- * @created 2006-04-07
- *
- * @author Andrae Muys
- *
- * @company <a href="mailto:mail at netymon.com">Netymon Pty Ltd</a>
- *
- * @copyright &copy;2006 Australian Commonwealth Government.
- *      All rights reserved.
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class CompoundPredicate {
-
-  // private final static Logger logger = Logger.getLogger(CompoundPredicate.class.getName());
-
-  private PElement predicate;
-  private List<PElement> objList;
-
-  /** Constructor */
-  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<PElement> getObjectList() {
-    return objList;
-  }
-
-  public PElement getPredicate() {
-    return predicate;
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/CompoundPredicate.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,92 @@
+/*
+ * 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
+ * Northrop Grumman Corporation. All Rights Reserved.
+ *
+ * This file is an original work and contains no Original Code.  It was
+ * developed by Netymon Pty Ltd under contract to the Australian 
+ * Commonwealth Government, Defense Science and Technology Organisation
+ * under contract #4500507038 and is contributed back to the Kowari/Mulgara
+ * Project as per clauses 4.1.3 and 4.1.4 of the above contract.
+ *
+ * Contributor(s): N/A.
+ *
+ * Copyright:
+ *   The copyright on this file is held by:
+ *     The Australian Commonwealth Government
+ *     Department of Defense
+ *   Developed by Netymon Pty Ltd
+ * Copyright (C) 2006
+ * The Australian Commonwealth Government
+ * Department of Defense
+ *
+ * [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.util.List;
+
+// Third party packages
+// import org.apache.log4j.Logger; 
+
+// Generated packages
+import org.mulgara.itql.node.*;
+
+/**
+ * A predicate element and a list of associated objects.  A list of these will be
+ * associated with a given subject element in a compound constraint.
+ *
+ * @created 2006-04-07
+ *
+ * @author Andrae Muys
+ *
+ * @company <a href="mailto:mail at netymon.com">Netymon Pty Ltd</a>
+ *
+ * @copyright &copy;2006 Australian Commonwealth Government.
+ *      All rights reserved.
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class CompoundPredicate {
+
+  // private final static Logger logger = Logger.getLogger(CompoundPredicate.class.getName());
+
+  private PElement predicate;
+  private List<PElement> objList;
+
+  /** Constructor */
+  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<PElement> getObjectList() {
+    return objList;
+  }
+
+  public PElement getPredicate() {
+    return predicate;
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,701 +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 compound-constraint syntax:
- *  The Australian Commonwealth Government
- *  Department of Defense
- *  Developed by Netymon Pty Ltd (mailto:mail at netymon.com)
- *  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.net.*;
-import java.util.ArrayList;
-import java.util.List;
-
-// Third party packages
-import org.apache.log4j.Logger; // Apache Log4J
-
-// Locally written packages
-
-// Automatically generated packages (SableCC)
-import org.mulgara.itql.analysis.*;
-import org.mulgara.itql.node.*;
-import org.mulgara.query.*;
-import org.mulgara.query.rdf.*;
-
-/**
- * A implementation of SableCC's Adapter which creates query constraint
- * depending on the type of object given (visitor pattern).  Tied heavily to
- * the ItqlInterpreter.
- *
- * @created 2004-06-18
- *
- * @author Andrew Newman
- *
- * @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>
- */
-public class ConstraintExpressionBuilder extends AnalysisAdapter {
-
-  /** The logger */
-  private final static Logger logger = Logger.getLogger(ConstraintExpressionBuilder.class.getName());
-
-  /** The internal result of parsing a constraint expression. */
-  private ConstraintExpression constraintExpression = null;
-
-  /** 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. */
-  private QueryException queryException = null;
-
-  /** The iTQL 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 ConstraintExpressionBuilder(SableCCInterpreter newInterpreter) {
-    interpreter = newInterpreter;
-  }
-
-  /**
-   * Returns the latest constraint expression or throws an exception if there
-   * was an error creating the last expression.  Once called the constraint
-   * expression object and exceptions are nulled.
-   *
-   * @throws QueryException if constraint does not represent a valid query
-   * @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 {
-    try {
-      ConstraintExpression tmpExpression = constraintExpression;
-
-      if (uriException != null) {
-        throw uriException;
-      } else if (queryException != null) {
-        throw queryException;
-      } else {
-        return tmpExpression;
-      }
-    } 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) {
-    constraintExpression = newConstraintExpression;
-  }
-
-
-  public void caseAConstraintConstraintFactor(AConstraintConstraintFactor rawConstraintFactor) {
-
-    if (logger.isDebugEnabled()) logger.debug("Found constraint constraint factor " + rawConstraintFactor);
-
-    // get the constraint
-    PConstraint constraint = ((AConstraintConstraintFactor)rawConstraintFactor).getConstraint();
-
-    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());
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found subject " + subject);
-        logger.debug("Found predicate " + predicate);
-        logger.debug("Found object " + object);
-      }
-
-      // check for an IN clause
-      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());
-
-        ConstraintElement model = toConstraintElement(inClause.getElement());
-        tmpConstraint = ConstraintFactory.newConstraint(subject, predicate, object, model);
-      } else {
-        tmpConstraint = ConstraintFactory.newConstraint(subject, predicate, object);
-      }
-
-      // handle negated constraints
-      if (((AConstraintConstraintFactor) rawConstraintFactor).getExclude() != null) {
-        tmpConstraint = new ConstraintNegation(tmpConstraint);
-      }
-
-      // Set new value.
-      if (logger.isDebugEnabled()) logger.debug("Setting constraint: " + tmpConstraint);
-
-      setConstraintExpression(tmpConstraint);
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } 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.
-   */
-  public void caseAExpressionConstraintFactor(AExpressionConstraintFactor rawConstraintFactor) {
-
-    try {
-      ConstraintExpression tmpConstraintExpression;
-
-      if (logger.isDebugEnabled()) logger.debug("Found factor expression constraint factor " + rawConstraintFactor);
-
-      // get the constraint expression
-      PConstraintExpression embeddedConstraintExpression =
-          ((AExpressionConstraintFactor)rawConstraintFactor).getConstraintExpression();
-
-      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint factor " + embeddedConstraintExpression);
-
-      // build the constraint expression
-      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);
-      }
-
-      setConstraintExpression(tmpConstraintExpression);
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } 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) {
-
-    try {
-      ConstraintExpression tmpConstraintExpression = null;
-
-      if (logger.isDebugEnabled()) logger.debug("Found factor of transitive expression" + rawConstraintFactor);
-
-      // get the constraint transitive
-      PTransitiveClause embeddedTransitiveConstraint =
-          ((ATransitiveConstraintFactor) rawConstraintFactor).getTransitiveClause();
-
-      if (embeddedTransitiveConstraint instanceof ATransitive1TransitiveClause) {
-
-        // build the transitive constraint expression
-        tmpConstraintExpression = new SingleTransitiveConstraint(
-            buildConstraint(((ATransitive1TransitiveClause)
-            embeddedTransitiveConstraint).getConstraint()));
-      } else if (embeddedTransitiveConstraint instanceof ATransitive2TransitiveClause) {
-
-        // build the transitive constraint expression
-        ATransitive2TransitiveClause tmpClause = (ATransitive2TransitiveClause)embeddedTransitiveConstraint;
-        Constraint constraint1 = buildConstraint(tmpClause.getConstraint1());
-        Constraint constraint2 = buildConstraint(tmpClause.getConstraint2());
-        tmpConstraintExpression = new TransitiveConstraint(constraint1, constraint2);
-      }
-
-      setConstraintExpression(tmpConstraintExpression);
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } 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);
-     try {
-       setConstraintExpression(
-           buildExistential(
-           interpreter.nextAnonVariable(),
-           rawFactor.getExistsExpression(),
-           (AInClause)rawFactor.getInClause()));
-     } catch (URISyntaxException eu) {
-       uriException = eu;
-     } catch (QueryException qe) {
-       queryException = qe;
-     }
-   }
-
-
-   /**
-    * Handle a concrete compound constraint.
-    */
-   public void caseACompoundConstraintFactor(ACompoundConstraintFactor rawFactor) {
-     if (logger.isDebugEnabled()) logger.debug("Found compound - constraint factor " + rawFactor);
-     try {
-       setConstraintExpression(
-           buildExistential(
-           toConstraintElement(rawFactor.getSubject()),
-           rawFactor.getExistsExpression(),
-           (AInClause)rawFactor.getInClause()));
-     } catch (URISyntaxException eu) {
-       uriException = eu;
-     } catch (QueryException qe) {
-       queryException = qe;
-     }
-   }
-           
-   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());
- 
-     CompoundPredListBuilder builder = new CompoundPredListBuilder();
-     rawTerm.apply(builder);
- 
-     if (logger.isDebugEnabled()) logger.debug("CompoundPredListBuilder built: " + builder.getPredLists());
- 
-     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<ConstraintExpression> argList = new ArrayList<ConstraintExpression>();
- 
-     for (CompoundPredicate plist: builder.getPredLists()) {
-       ConstraintElement predicate = toConstraintElement(plist.getPredicate());
- 
-       for (PElement oelem: plist.getObjectList()) {
-         ConstraintElement object = toConstraintElement(oelem);
- 
-         if (model == null) {
-           argList.add(ConstraintFactory.newConstraint(subject, predicate, object));
-         } else {
-           argList.add(ConstraintFactory.newConstraint(subject, predicate, object, model));
-         }
-       }
-     }
- 
-     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) {
-
-    try {
-      // Build the walk constraint
-      AWalk1WalkClause embeddedWalkConstraint =
-          (AWalk1WalkClause)((AWalkConstraintFactor)rawConstraintFactor).getWalkClause();
-
-      ConstraintExpression tmpConstraintExpression = new WalkConstraint(
-          buildConstraint(embeddedWalkConstraint.getConstraint1()),
-          buildConstraint(embeddedWalkConstraint.getConstraint2()));
-
-      setConstraintExpression(tmpConstraintExpression);
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } 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) {
-
-    try {
-      if (logger.isDebugEnabled()) logger.debug("Found OR constraint expression " +rawConstraintExpression);
-
-      // get the OR constraint expression
-      PConstraintExpression orConstraintExpression =
-          ((AOrConstraintExpression)rawConstraintExpression).getConstraintExpression();
-
-      // get the constraint term
-      PConstraintTerm constraintTerm =
-          ((AOrConstraintExpression)rawConstraintExpression).getConstraintTerm();
-
-      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);
-
-      // get the LHS and RHS operands of the disjunction
-      orConstraintExpression.apply((Switch)builder);
-      ConstraintExpression lhs = builder.getConstraintExpression();
-      constraintTerm.apply((Switch)builder);
-      ConstraintExpression rhs = builder.getConstraintExpression();
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Resolved LHS disjunction operand " + lhs);
-        logger.debug("Resolved RHS disjunction operand " + rhs);
-      }
-
-      // apply the disjunction
-      setConstraintExpression(new ConstraintDisjunction(lhs, rhs));
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } catch (QueryException qe) {
-      queryException = qe;
-    }
-  }
-
-  /**
-   * Handle a term constraint.  Will set URIException or QueryException if
-   * an exception occurs.
-   *
-   * @param rawConstraintExpression a term constraint.
-   */
-  public void caseATermConstraintExpression(ATermConstraintExpression rawConstraintExpression) {
-
-    try {
-      if (logger.isDebugEnabled()) logger.debug("Found term constraint expression " + rawConstraintExpression);
-
-      // get the constraint term
-      PConstraintTerm constraintTerm =
-          ((ATermConstraintExpression) rawConstraintExpression).getConstraintTerm();
-
-      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint term " + constraintTerm);
-
-      // Create a new builder.
-      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
-      constraintTerm.apply((Switch)builder);
-
-      // drill down into the constraint term
-      setConstraintExpression(builder.getConstraintExpression());
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } 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) {
-
-    try {
-      if (logger.isDebugEnabled()) logger.debug("Found dterm contraint term " + rawConstraintTerm);
-
-      // get the constraint factor
-      PConstraintDterm constraintDterm =
-          ((ADtermConstraintTerm)rawConstraintTerm).getConstraintDterm();
-
-      ConstraintExpression tmpConstraintExpression = null;
-
-      // drill down into the constraint factor
-      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
-      constraintDterm.apply((Switch)builder);
-      tmpConstraintExpression = builder.getConstraintExpression();
-      setConstraintExpression(tmpConstraintExpression);
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with constraint factor " + constraintDterm);
-        logger.debug("Got: " + tmpConstraintExpression);
-      }
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } catch (QueryException qe) {
-      queryException = qe;
-    }
-  }
-
-
-  /**
-   * Handle a AND constraint term.  Will set URIException or QueryException if
-   * an exception occurs.
-   *
-   * @param rawConstraintTerm a AND constraint term.
-   */
-  public void caseAAndConstraintTerm(AAndConstraintTerm rawConstraintTerm) {
-
-    try {
-
-      if (logger.isDebugEnabled()) logger.debug("Found AND contraint term " + rawConstraintTerm);
-
-      // get the constraint term
-      PConstraintTerm constraintTerm =
-          ((AAndConstraintTerm) rawConstraintTerm).getConstraintTerm();
-
-      // get the constraint factor
-      PConstraintDterm constraintDterm =
-          ((AAndConstraintTerm) rawConstraintTerm).getConstraintDterm();
-
-      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint term " + constraintTerm +
-            " & constraint factor " + constraintDterm);
-
-      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
-
-      // get the LHS and RHS operands of the conjunction
-      constraintTerm.apply((Switch)builder);
-      ConstraintExpression lhs = builder.getConstraintExpression();
-
-      // Create another constraint builder and assign to RHS.
-      constraintDterm.apply((Switch) builder);
-      ConstraintExpression rhs = builder.getConstraintExpression();
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Resolved LHS conjunction operand " + lhs);
-        logger.debug("Resolved RHS conjunction operand " + rhs);
-      }
-
-      // apply the conjunction
-      setConstraintExpression(new ConstraintConjunction(lhs, rhs));
-
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } 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) {
-
-    try {
-      logger.debug("Found factor contraint term " + rawConstraintTerm);
-
-      // get the constraint factor
-      PConstraintFactor constraintFactor =
-          ((AFactorConstraintDterm) rawConstraintTerm).getConstraintFactor();
-
-      ConstraintExpression tmpConstraintExpression = null;
-
-      // drill down into the constraint factor
-      ConstraintExpressionBuilder builder =
-          new ConstraintExpressionBuilder(interpreter);
-      constraintFactor.apply((Switch) builder);
-      tmpConstraintExpression = builder.getConstraintExpression();
-      setConstraintExpression(tmpConstraintExpression);
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with constraint factor " + constraintFactor);
-        logger.debug("Got: " + tmpConstraintExpression);
-      }
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } catch (QueryException qe) {
-      queryException = qe;
-    }
-  }
-
-  /**
-   * Handle a MINUS constraint dterm.  Will set URIException or QueryException if
-   * an exception occurs.
-   *
-   * @param rawConstraintTerm a MINUS constraint dterm.
-   */
-  public void caseAMinusConstraintDterm(AMinusConstraintDterm rawConstraintTerm) {
-
-    try {
-
-      if (logger.isDebugEnabled()) logger.debug("Found MINUS contraint dterm " + rawConstraintTerm);
-
-      // get the minuend expression
-      PConstraintDterm minuendExpr =
-          ((AMinusConstraintDterm) rawConstraintTerm).getMinuend();
-
-      // get the subtrahend expression
-      PConstraintFactor subtrahendExpr =
-          ((AMinusConstraintDterm) rawConstraintTerm).getSubtrahend();
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with minuend " + minuendExpr + " & subtrahend " + subtrahendExpr);
-      }
-
-      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
-
-      // get the LHS and RHS operands of the conjunction
-      minuendExpr.apply((Switch)builder);
-      ConstraintExpression minuend = builder.getConstraintExpression();
-
-      // Create another constraint builder and assign to RHS.
-      subtrahendExpr.apply((Switch)builder);
-      ConstraintExpression subtrahend = builder.getConstraintExpression();
-
-      if (logger.isDebugEnabled()) {
-        logger.debug("Resolved minuend operand " + minuend);
-        logger.debug("Resolved subtrahend operand " + subtrahend);
-      }
-
-      // apply the conjunction
-      setConstraintExpression(new ConstraintDifference(minuend, subtrahend));
-    } catch (URISyntaxException use) {
-      uriException = use;
-    } catch (QueryException qe) {
-      queryException = qe;
-    }
-  }
-
-
-  /**
-   * Helper method used to build up a Constraint object from a SableCC
-   * PConstraint object.
-   *
-   * @param pconstraint The parser constraint object to convert.
-   * @return A Constraint object for use in transitive constraints.
-   * @throws QueryException if the constraint contains a NOT or IN section.
-   */
-  Constraint buildConstraint(PConstraint pconstraint) throws QueryException,
-      URISyntaxException {
-
-    if (logger.isDebugEnabled()) logger.debug("Found constraint " + pconstraint + ", resolving components");
-
-    // get the constraint's components
-    ConstraintElement subject =
-        toConstraintElement(((AConstraint) pconstraint).getSubject());
-    ConstraintElement predicate =
-        toConstraintElement(((AConstraint) pconstraint).getPredicate());
-    ConstraintElement object =
-        toConstraintElement(((AConstraint) pconstraint).getObject());
-
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found subject " + subject);
-      logger.debug("Found predicate " + predicate);
-      logger.debug("Found object " + object);
-    }
-
-    // check for an IN - this is illegal
-    if (((AConstraint)pconstraint).getInClause() != null) {
-      throw new QueryException("Illegal in clause on transitive constraint.");
-    }
-
-    // bundle them into a constraint (order is probably important here...?)
-    return ConstraintFactory.newConstraint(subject, predicate, object);
-  }
-
-
-  /**
-   * Constructs a {@link org.mulgara.query.ConstraintElement} from a
-   * {@link org.mulgara.itql.node.PElement}.
-   *
-   * @param element an element of a constraint (variable, resource or literal)
-   * @return a constraint element for the given <code>element</code>
-   * @throws QueryException if <code>element</code> is a
-   *      {@link org.mulgara.itql.node.AResourceElement} 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.AResourceElement} whose text doesn't
-   *      conform to
-   *      <a href="http://www.isi.edu/in-notes/rfc2396.txt">RFC 2396</a>
-   */
-  private ConstraintElement toConstraintElement(PElement element) 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 constraint element");
-
-    // create a constraint element to return
-    ConstraintElement constraintElement = null;
-
-    // get the appropriate element type
-    if (element instanceof AVariableElement) {
-
-      // get the name of the variable
-      PVariable rawVariable = ((AVariableElement) element).getVariable();
-      String variableName = ((AVariable) rawVariable).getIdentifier().getText();
-
-      if (logger.isDebugEnabled()) logger.debug("Resolved " + element + " to variable " + variableName);
-
-      // create a new variable
-      constraintElement = new Variable(variableName);
-
-    } else if (element instanceof AResourceElement) {
-
-      // create a new resource
-      constraintElement = new URIReferenceImpl(interpreter.toURI(
-          ((AResourceElement) element).getResource()));
-
-    } else if (element instanceof ALiteralElement) {
-
-      // create a new literal
-      constraintElement = interpreter.toLiteralImpl(((ALiteralElement) element).
-          getLiteral());
-    }
-
-    // return the constraint element
-    return constraintElement;
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ConstraintExpressionBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,701 @@
+/*
+ * 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 compound-constraint syntax:
+ *  The Australian Commonwealth Government
+ *  Department of Defense
+ *  Developed by Netymon Pty Ltd (mailto:mail at netymon.com)
+ *  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.net.*;
+import java.util.ArrayList;
+import java.util.List;
+
+// Third party packages
+import org.apache.log4j.Logger; // Apache Log4J
+
+// Locally written packages
+
+// Automatically generated packages (SableCC)
+import org.mulgara.itql.analysis.*;
+import org.mulgara.itql.node.*;
+import org.mulgara.query.*;
+import org.mulgara.query.rdf.*;
+
+/**
+ * A implementation of SableCC's Adapter which creates query constraint
+ * depending on the type of object given (visitor pattern).  Tied heavily to
+ * the ItqlInterpreter.
+ *
+ * @created 2004-06-18
+ *
+ * @author Andrew Newman
+ *
+ * @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>
+ */
+public class ConstraintExpressionBuilder extends AnalysisAdapter {
+
+  /** The logger */
+  private final static Logger logger = Logger.getLogger(ConstraintExpressionBuilder.class.getName());
+
+  /** The internal result of parsing a constraint expression. */
+  private ConstraintExpression constraintExpression = null;
+
+  /** 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. */
+  private QueryException queryException = null;
+
+  /** The iTQL 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 ConstraintExpressionBuilder(SableCCInterpreter newInterpreter) {
+    interpreter = newInterpreter;
+  }
+
+  /**
+   * Returns the latest constraint expression or throws an exception if there
+   * was an error creating the last expression.  Once called the constraint
+   * expression object and exceptions are nulled.
+   *
+   * @throws QueryException if constraint does not represent a valid query
+   * @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 {
+    try {
+      ConstraintExpression tmpExpression = constraintExpression;
+
+      if (uriException != null) {
+        throw uriException;
+      } else if (queryException != null) {
+        throw queryException;
+      } else {
+        return tmpExpression;
+      }
+    } 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) {
+    constraintExpression = newConstraintExpression;
+  }
+
+
+  public void caseAConstraintConstraintFactor(AConstraintConstraintFactor rawConstraintFactor) {
+
+    if (logger.isDebugEnabled()) logger.debug("Found constraint constraint factor " + rawConstraintFactor);
+
+    // get the constraint
+    PConstraint constraint = ((AConstraintConstraintFactor)rawConstraintFactor).getConstraint();
+
+    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());
+
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found subject " + subject);
+        logger.debug("Found predicate " + predicate);
+        logger.debug("Found object " + object);
+      }
+
+      // check for an IN clause
+      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());
+
+        ConstraintElement model = toConstraintElement(inClause.getElement());
+        tmpConstraint = ConstraintFactory.newConstraint(subject, predicate, object, model);
+      } else {
+        tmpConstraint = ConstraintFactory.newConstraint(subject, predicate, object);
+      }
+
+      // handle negated constraints
+      if (((AConstraintConstraintFactor) rawConstraintFactor).getExclude() != null) {
+        tmpConstraint = new ConstraintNegation(tmpConstraint);
+      }
+
+      // Set new value.
+      if (logger.isDebugEnabled()) logger.debug("Setting constraint: " + tmpConstraint);
+
+      setConstraintExpression(tmpConstraint);
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } 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.
+   */
+  public void caseAExpressionConstraintFactor(AExpressionConstraintFactor rawConstraintFactor) {
+
+    try {
+      ConstraintExpression tmpConstraintExpression;
+
+      if (logger.isDebugEnabled()) logger.debug("Found factor expression constraint factor " + rawConstraintFactor);
+
+      // get the constraint expression
+      PConstraintExpression embeddedConstraintExpression =
+          ((AExpressionConstraintFactor)rawConstraintFactor).getConstraintExpression();
+
+      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint factor " + embeddedConstraintExpression);
+
+      // build the constraint expression
+      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);
+      }
+
+      setConstraintExpression(tmpConstraintExpression);
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } 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) {
+
+    try {
+      ConstraintExpression tmpConstraintExpression = null;
+
+      if (logger.isDebugEnabled()) logger.debug("Found factor of transitive expression" + rawConstraintFactor);
+
+      // get the constraint transitive
+      PTransitiveClause embeddedTransitiveConstraint =
+          ((ATransitiveConstraintFactor) rawConstraintFactor).getTransitiveClause();
+
+      if (embeddedTransitiveConstraint instanceof ATransitive1TransitiveClause) {
+
+        // build the transitive constraint expression
+        tmpConstraintExpression = new SingleTransitiveConstraint(
+            buildConstraint(((ATransitive1TransitiveClause)
+            embeddedTransitiveConstraint).getConstraint()));
+      } else if (embeddedTransitiveConstraint instanceof ATransitive2TransitiveClause) {
+
+        // build the transitive constraint expression
+        ATransitive2TransitiveClause tmpClause = (ATransitive2TransitiveClause)embeddedTransitiveConstraint;
+        Constraint constraint1 = buildConstraint(tmpClause.getConstraint1());
+        Constraint constraint2 = buildConstraint(tmpClause.getConstraint2());
+        tmpConstraintExpression = new TransitiveConstraint(constraint1, constraint2);
+      }
+
+      setConstraintExpression(tmpConstraintExpression);
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } 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);
+     try {
+       setConstraintExpression(
+           buildExistential(
+           interpreter.nextAnonVariable(),
+           rawFactor.getExistsExpression(),
+           (AInClause)rawFactor.getInClause()));
+     } catch (URISyntaxException eu) {
+       uriException = eu;
+     } catch (QueryException qe) {
+       queryException = qe;
+     }
+   }
+
+
+   /**
+    * Handle a concrete compound constraint.
+    */
+   public void caseACompoundConstraintFactor(ACompoundConstraintFactor rawFactor) {
+     if (logger.isDebugEnabled()) logger.debug("Found compound - constraint factor " + rawFactor);
+     try {
+       setConstraintExpression(
+           buildExistential(
+           toConstraintElement(rawFactor.getSubject()),
+           rawFactor.getExistsExpression(),
+           (AInClause)rawFactor.getInClause()));
+     } catch (URISyntaxException eu) {
+       uriException = eu;
+     } catch (QueryException qe) {
+       queryException = qe;
+     }
+   }
+           
+   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());
+ 
+     CompoundPredListBuilder builder = new CompoundPredListBuilder();
+     rawTerm.apply(builder);
+ 
+     if (logger.isDebugEnabled()) logger.debug("CompoundPredListBuilder built: " + builder.getPredLists());
+ 
+     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<ConstraintExpression> argList = new ArrayList<ConstraintExpression>();
+ 
+     for (CompoundPredicate plist: builder.getPredLists()) {
+       ConstraintElement predicate = toConstraintElement(plist.getPredicate());
+ 
+       for (PElement oelem: plist.getObjectList()) {
+         ConstraintElement object = toConstraintElement(oelem);
+ 
+         if (model == null) {
+           argList.add(ConstraintFactory.newConstraint(subject, predicate, object));
+         } else {
+           argList.add(ConstraintFactory.newConstraint(subject, predicate, object, model));
+         }
+       }
+     }
+ 
+     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) {
+
+    try {
+      // Build the walk constraint
+      AWalk1WalkClause embeddedWalkConstraint =
+          (AWalk1WalkClause)((AWalkConstraintFactor)rawConstraintFactor).getWalkClause();
+
+      ConstraintExpression tmpConstraintExpression = new WalkConstraint(
+          buildConstraint(embeddedWalkConstraint.getConstraint1()),
+          buildConstraint(embeddedWalkConstraint.getConstraint2()));
+
+      setConstraintExpression(tmpConstraintExpression);
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } 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) {
+
+    try {
+      if (logger.isDebugEnabled()) logger.debug("Found OR constraint expression " +rawConstraintExpression);
+
+      // get the OR constraint expression
+      PConstraintExpression orConstraintExpression =
+          ((AOrConstraintExpression)rawConstraintExpression).getConstraintExpression();
+
+      // get the constraint term
+      PConstraintTerm constraintTerm =
+          ((AOrConstraintExpression)rawConstraintExpression).getConstraintTerm();
+
+      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);
+
+      // get the LHS and RHS operands of the disjunction
+      orConstraintExpression.apply((Switch)builder);
+      ConstraintExpression lhs = builder.getConstraintExpression();
+      constraintTerm.apply((Switch)builder);
+      ConstraintExpression rhs = builder.getConstraintExpression();
+
+      if (logger.isDebugEnabled()) {
+        logger.debug("Resolved LHS disjunction operand " + lhs);
+        logger.debug("Resolved RHS disjunction operand " + rhs);
+      }
+
+      // apply the disjunction
+      setConstraintExpression(new ConstraintDisjunction(lhs, rhs));
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } catch (QueryException qe) {
+      queryException = qe;
+    }
+  }
+
+  /**
+   * Handle a term constraint.  Will set URIException or QueryException if
+   * an exception occurs.
+   *
+   * @param rawConstraintExpression a term constraint.
+   */
+  public void caseATermConstraintExpression(ATermConstraintExpression rawConstraintExpression) {
+
+    try {
+      if (logger.isDebugEnabled()) logger.debug("Found term constraint expression " + rawConstraintExpression);
+
+      // get the constraint term
+      PConstraintTerm constraintTerm =
+          ((ATermConstraintExpression) rawConstraintExpression).getConstraintTerm();
+
+      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint term " + constraintTerm);
+
+      // Create a new builder.
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
+      constraintTerm.apply((Switch)builder);
+
+      // drill down into the constraint term
+      setConstraintExpression(builder.getConstraintExpression());
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } 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) {
+
+    try {
+      if (logger.isDebugEnabled()) logger.debug("Found dterm contraint term " + rawConstraintTerm);
+
+      // get the constraint factor
+      PConstraintDterm constraintDterm =
+          ((ADtermConstraintTerm)rawConstraintTerm).getConstraintDterm();
+
+      ConstraintExpression tmpConstraintExpression = null;
+
+      // drill down into the constraint factor
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
+      constraintDterm.apply((Switch)builder);
+      tmpConstraintExpression = builder.getConstraintExpression();
+      setConstraintExpression(tmpConstraintExpression);
+
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with constraint factor " + constraintDterm);
+        logger.debug("Got: " + tmpConstraintExpression);
+      }
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } catch (QueryException qe) {
+      queryException = qe;
+    }
+  }
+
+
+  /**
+   * Handle a AND constraint term.  Will set URIException or QueryException if
+   * an exception occurs.
+   *
+   * @param rawConstraintTerm a AND constraint term.
+   */
+  public void caseAAndConstraintTerm(AAndConstraintTerm rawConstraintTerm) {
+
+    try {
+
+      if (logger.isDebugEnabled()) logger.debug("Found AND contraint term " + rawConstraintTerm);
+
+      // get the constraint term
+      PConstraintTerm constraintTerm =
+          ((AAndConstraintTerm) rawConstraintTerm).getConstraintTerm();
+
+      // get the constraint factor
+      PConstraintDterm constraintDterm =
+          ((AAndConstraintTerm) rawConstraintTerm).getConstraintDterm();
+
+      if (logger.isDebugEnabled()) logger.debug("Recursing with constraint term " + constraintTerm +
+            " & constraint factor " + constraintDterm);
+
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
+
+      // get the LHS and RHS operands of the conjunction
+      constraintTerm.apply((Switch)builder);
+      ConstraintExpression lhs = builder.getConstraintExpression();
+
+      // Create another constraint builder and assign to RHS.
+      constraintDterm.apply((Switch) builder);
+      ConstraintExpression rhs = builder.getConstraintExpression();
+
+      if (logger.isDebugEnabled()) {
+        logger.debug("Resolved LHS conjunction operand " + lhs);
+        logger.debug("Resolved RHS conjunction operand " + rhs);
+      }
+
+      // apply the conjunction
+      setConstraintExpression(new ConstraintConjunction(lhs, rhs));
+
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } 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) {
+
+    try {
+      logger.debug("Found factor contraint term " + rawConstraintTerm);
+
+      // get the constraint factor
+      PConstraintFactor constraintFactor =
+          ((AFactorConstraintDterm) rawConstraintTerm).getConstraintFactor();
+
+      ConstraintExpression tmpConstraintExpression = null;
+
+      // drill down into the constraint factor
+      ConstraintExpressionBuilder builder =
+          new ConstraintExpressionBuilder(interpreter);
+      constraintFactor.apply((Switch) builder);
+      tmpConstraintExpression = builder.getConstraintExpression();
+      setConstraintExpression(tmpConstraintExpression);
+
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with constraint factor " + constraintFactor);
+        logger.debug("Got: " + tmpConstraintExpression);
+      }
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } catch (QueryException qe) {
+      queryException = qe;
+    }
+  }
+
+  /**
+   * Handle a MINUS constraint dterm.  Will set URIException or QueryException if
+   * an exception occurs.
+   *
+   * @param rawConstraintTerm a MINUS constraint dterm.
+   */
+  public void caseAMinusConstraintDterm(AMinusConstraintDterm rawConstraintTerm) {
+
+    try {
+
+      if (logger.isDebugEnabled()) logger.debug("Found MINUS contraint dterm " + rawConstraintTerm);
+
+      // get the minuend expression
+      PConstraintDterm minuendExpr =
+          ((AMinusConstraintDterm) rawConstraintTerm).getMinuend();
+
+      // get the subtrahend expression
+      PConstraintFactor subtrahendExpr =
+          ((AMinusConstraintDterm) rawConstraintTerm).getSubtrahend();
+
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with minuend " + minuendExpr + " & subtrahend " + subtrahendExpr);
+      }
+
+      ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(interpreter);
+
+      // get the LHS and RHS operands of the conjunction
+      minuendExpr.apply((Switch)builder);
+      ConstraintExpression minuend = builder.getConstraintExpression();
+
+      // Create another constraint builder and assign to RHS.
+      subtrahendExpr.apply((Switch)builder);
+      ConstraintExpression subtrahend = builder.getConstraintExpression();
+
+      if (logger.isDebugEnabled()) {
+        logger.debug("Resolved minuend operand " + minuend);
+        logger.debug("Resolved subtrahend operand " + subtrahend);
+      }
+
+      // apply the conjunction
+      setConstraintExpression(new ConstraintDifference(minuend, subtrahend));
+    } catch (URISyntaxException use) {
+      uriException = use;
+    } catch (QueryException qe) {
+      queryException = qe;
+    }
+  }
+
+
+  /**
+   * Helper method used to build up a Constraint object from a SableCC
+   * PConstraint object.
+   *
+   * @param pconstraint The parser constraint object to convert.
+   * @return A Constraint object for use in transitive constraints.
+   * @throws QueryException if the constraint contains a NOT or IN section.
+   */
+  Constraint buildConstraint(PConstraint pconstraint) throws QueryException,
+      URISyntaxException {
+
+    if (logger.isDebugEnabled()) logger.debug("Found constraint " + pconstraint + ", resolving components");
+
+    // get the constraint's components
+    ConstraintElement subject =
+        toConstraintElement(((AConstraint) pconstraint).getSubject());
+    ConstraintElement predicate =
+        toConstraintElement(((AConstraint) pconstraint).getPredicate());
+    ConstraintElement object =
+        toConstraintElement(((AConstraint) pconstraint).getObject());
+
+    if (logger.isDebugEnabled()) {
+      logger.debug("Found subject " + subject);
+      logger.debug("Found predicate " + predicate);
+      logger.debug("Found object " + object);
+    }
+
+    // check for an IN - this is illegal
+    if (((AConstraint)pconstraint).getInClause() != null) {
+      throw new QueryException("Illegal in clause on transitive constraint.");
+    }
+
+    // bundle them into a constraint (order is probably important here...?)
+    return ConstraintFactory.newConstraint(subject, predicate, object);
+  }
+
+
+  /**
+   * Constructs a {@link org.mulgara.query.ConstraintElement} from a
+   * {@link org.mulgara.itql.node.PElement}.
+   *
+   * @param element an element of a constraint (variable, resource or literal)
+   * @return a constraint element for the given <code>element</code>
+   * @throws QueryException if <code>element</code> is a
+   *      {@link org.mulgara.itql.node.AResourceElement} 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.AResourceElement} whose text doesn't
+   *      conform to
+   *      <a href="http://www.isi.edu/in-notes/rfc2396.txt">RFC 2396</a>
+   */
+  private ConstraintElement toConstraintElement(PElement element) 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 constraint element");
+
+    // create a constraint element to return
+    ConstraintElement constraintElement = null;
+
+    // get the appropriate element type
+    if (element instanceof AVariableElement) {
+
+      // get the name of the variable
+      PVariable rawVariable = ((AVariableElement) element).getVariable();
+      String variableName = ((AVariable) rawVariable).getIdentifier().getText();
+
+      if (logger.isDebugEnabled()) logger.debug("Resolved " + element + " to variable " + variableName);
+
+      // create a new variable
+      constraintElement = new Variable(variableName);
+
+    } else if (element instanceof AResourceElement) {
+
+      // create a new resource
+      constraintElement = new URIReferenceImpl(interpreter.toURI(
+          ((AResourceElement) element).getResource()));
+
+    } else if (element instanceof ALiteralElement) {
+
+      // create a new literal
+      constraintElement = interpreter.toLiteralImpl(((ALiteralElement) element).
+          getLiteral());
+    }
+
+    // return the constraint element
+    return constraintElement;
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,738 +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 org.apache.log4j.Logger;
-
-// Automatically generated packages (SableCC)
-import org.mulgara.itql.analysis.DepthFirstAdapter;
-import org.mulgara.itql.node.*;
-
-/**
- * Prints help for ITQL commands.
- *
- * @created 2001-09-10
- *
- * @author Tom Adams
- *
- * @version $Revision: 1.9 $
- *
- * @modified $Date: 2005/06/26 12:48:09 $ 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
- *      Software Pty Ltd</a>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class HelpPrinter {
-
-  //
-  // Constants
-  //
-
-  /**
-   * the category to log to
-   */
-  private final static Logger log = Logger.getLogger(HelpPrinter.class);
-
-  /**
-   * Get line separator.
-   */
-  private static final String eol = System.getProperty("line.separator");
-
-  /**
-   * message to print if a command does not have a help message
-   */
-  private final static String NO_HELP_MESSAGE =
-      eol + "No help exists for this command." + eol;
-
-  //
-  // Public API
-  //
-
-  /**
-   * Returns a help message for the given <code>command</code> (prefix).
-   *
-   * @param command the comand (prefix) to retrieve help for
-   * @return The Help value
-   */
-  public static String getHelp(PCommandPrefix command) {
-
-    // log that we're about to print the help
-    log.debug("Getting help for command - " + command);
-
-    // the help message
-    final StringBuffer helpMsg = new StringBuffer();
-
-    // delegate to the correct help printing method
-    command.apply(new DepthFirstAdapter() {
-
-      // we've got an empty help command (they want basic help)
-      public void caseAEmptyCommandPrefix(AEmptyCommandPrefix node) {
-
-        helpMsg.append(printDefaultHelp());
-      }
-
-      // caseAEmptyCommandPrefix()
-
-      /*
-             // NOTE: we need to hack the states in the grammar to get help on comments
-             // we've got a comment
-           public void caseACommentCommandPrefix(ACommentCommandPrefix node) {
-               helpMsg.append(printCommentHelp());
-             } // caseACommentCommandPrefix()
-       */
-
-      // we've got an alias
-      public void caseAAliasCommandPrefix(AAliasCommandPrefix node) {
-
-        helpMsg.append(printAliasHelp());
-      }
-
-      // caseAAliasCommandPrefix()
-      // we've got a create
-      public void caseACreateCommandPrefix(ACreateCommandPrefix node) {
-
-        helpMsg.append(printCreateHelp());
-      }
-
-      // caseACreateCommandPrefix()
-      // we've got a delete
-      public void caseADeleteCommandPrefix(ADeleteCommandPrefix node) {
-
-        helpMsg.append(printDeleteHelp());
-      }
-
-      // caseADeleteCommandPrefix()
-
-      /*
-             // NOTE: we don't currently support the directory command
-             // we've got directory
-           public void caseADirectoryCommandPrefix(ADirectoryCommandPrefix node) {
-               helpMsg.append(printDirectoryHelp());
-             } // caseADirectoryCommandPrefix()
-       */
-
-      // we've got a drop
-      public void caseADropCommandPrefix(ADropCommandPrefix node) {
-
-        helpMsg.append(printDropHelp());
-      }
-
-      // caseADropCommandPrefix()
-      // we've got an execute
-      public void caseAExecuteCommandPrefix(AExecuteCommandPrefix node) {
-
-        helpMsg.append(printExecuteHelp());
-      }
-
-      // caseAExecuteCommandPrefix()
-      // we've got a help
-      public void caseAHelpCommandPrefix(AHelpCommandPrefix node) {
-
-        helpMsg.append(printHelpHelp());
-      }
-
-      // caseAHelpCommandPrefix()
-      // we've got an insert
-      public void caseAInsertCommandPrefix(AInsertCommandPrefix node) {
-
-        helpMsg.append(printInsertHelp());
-      }
-
-      // caseAInsertCommandPrefix()
-      // we've got a load
-      public void caseALoadCommandPrefix(ALoadCommandPrefix node) {
-
-        helpMsg.append(printLoadHelp());
-      }
-
-      // caseALoadCommandPrefix()
-      // we've got a quit
-      public void caseAQuitCommandPrefix(AQuitCommandPrefix node) {
-
-        helpMsg.append(printQuitHelp());
-      }
-
-      // caseAQuitCommandPrefix()
-      // we've got a select
-      public void caseASelectCommandPrefix(ASelectCommandPrefix node) {
-
-        helpMsg.append(printSelectHelp());
-      }
-
-      // caseASelectCommandPrefix()
-      // we've got a set
-      public void caseASetCommandPrefix(ASetCommandPrefix node) {
-
-        helpMsg.append(printSetHelp());
-      }
-
-      // caseASetCommandPrefix()
-      // we've got an su
-      public void caseASuCommandPrefix(ASuCommandPrefix node) {
-
-        helpMsg.append(printSuHelp());
-      }
-
-      // caseASuCommandPrefix()
-      // we've got a backup
-      public void caseABackupCommandPrefix(ABackupCommandPrefix node) {
-
-        helpMsg.append(printBackupHelp());
-      }
-
-      // caseABackupCommandPrefix()
-      // we've got a restore
-      public void caseARestoreCommandPrefix(ARestoreCommandPrefix node) {
-
-        helpMsg.append(printRestoreHelp());
-      }
-
-      // caseARestoreCommandPrefix()
-      // we've got a commit
-      public void caseACommitCommandPrefix(ACommitCommandPrefix node) {
-
-        helpMsg.append(printCommitHelp());
-      }
-
-      // caseACommitCommandPrefix()
-      // we've got a rollback
-      public void caseARollbackCommandPrefix(ARollbackCommandPrefix node) {
-
-        helpMsg.append(printRollbackHelp());
-      }
-
-      // caseARollbackCommandPrefix()
-
-      // caseAApplyCommandPrefix()
-      public void caseAApplyCommandPrefix(AApplyCommandPrefix node) {
-
-        helpMsg.append(printApplyHelp());
-      }
-
-    });
-
-    // make sure that we got a message back (we may have implemented a new
-    // command but forgot to add a method to the visitor pattern above)
-    if (helpMsg.length() == 0) {
-
-      // append a "no help avaliable" message
-      helpMsg.append(NO_HELP_MESSAGE);
-    }
-
-    // end if
-    // log that we're returning help
-    log.debug("Returning help for command " + command);
-
-    // returning
-    return helpMsg.toString();
-  }
-
-  // getHelp()
-  //
-  // Internal methods
-  //
-
-  /**
-   * Print the default help message.
-   *
-   * @return the default help
-   */
-  private static StringBuffer printDefaultHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing default help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append(eol + "Valid commands are:" + eol + eol);
-
-    //helpMsg.append("  #       comment");
-    helpMsg.append("  su       authenticate a user" + eol);
-    helpMsg.append("  set      set a property" + eol);
-    helpMsg.append("  execute  execute an iTQL script" + eol);
-    helpMsg.append("  alias    define an alias" + eol);
-    helpMsg.append("  create   create a model" + eol);
-    helpMsg.append("  commit   commits a transaction" + eol);
-    helpMsg.append("  drop     drop an entire resource" + eol);
-    helpMsg.append("  insert   insert a set of triples" + eol);
-    helpMsg.append("  delete   delete a set of triples" + eol);
-    helpMsg.append("  load     load contents of a file          " + eol);
-    helpMsg.append("  backup   backup the contents of a server to a file" + eol);
-    helpMsg.append("  restore  restore a server from a backup file" + eol);
-    helpMsg.append("  rollback rolls back a transaction" + eol);
-    helpMsg.append("  select   perform a query" + eol);
-    helpMsg.append("  set      sets various options" + eol);
-    helpMsg.append("  apply    applies a set of rules" + eol);
-    helpMsg.append("  quit     end the ITQL session" + eol);
-    helpMsg.append("  help     display this help screen" + eol + eol);
-    helpMsg.append("You can also get detailed help on each command:" + eol + eol);
-    helpMsg.append("  $ help <command> ;" + eol + eol);
-    helpMsg.append("For example, to display help on the select command:" +
-        eol + eol);
-    helpMsg.append("  $ help select ;" + eol + eol);
-    helpMsg.append("Note. All commands must be terminated with \";\"." + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printDefaultHelp()
-
-  /**
-   * Print the su help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printSuHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing su help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nAuthenticates a user." + eol);
-    helpMsg.append(eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> su <ldap://bar.org> fred Fo0Bar ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printSuHelp()
-
-  /**
-   * Print the set help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printSetHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing ser help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append(eol + "Sets an iTQL interpreter option." + eol);
-    helpMsg.append(eol);
-    helpMsg.append("The following options are supported:" + eol + eol);
-
-    //helpMsg.append("  o echo - displays command results" + eol);
-    //helpMsg.append("  o statistics - " + eol);
-    //helpMsg.append("  o stoponerror - " + eol);
-    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("  TQL> set time on ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printSetHelp()
-
-  /**
-   * Print the execute help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printExecuteHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing execute help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nExecutes an iTQL script." + eol);
-    helpMsg.append(eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> execute " +
-        "<file:/usr/local/mulgara/sample/itql/loaddc.itql> ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printExecuteHelp()
-
-  /**
-   * Print the alias help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printAliasHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing alias help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nCreates an alias to a URL, model or database." + eol);
-    helpMsg.append(eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> alias <http://www.w3.org/2000/01/rdf-schema#> as " +
-        "rdfs ;" + eol);
-    helpMsg.append("  TQL> select $subj $obj from " +
-        "<http://purl.org/dc/elements/1.1/> where $subj <rdfs:label> $obj ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printAliasHelp()
-
-  /**
-   * Print the create help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printCreateHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing create help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append(eol + "Creates a new (empty) model." + eol);
-    helpMsg.append(eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> create <rmi://localhost/foo#bar> ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printCreateHelp()
-
-  /**
-   * Print the drop help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printDropHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing drop help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append(eol + "Drops a model." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> drop <rmi://localhost/foo#bar> ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printDropHelp()
-
-  /**
-   * Print the insert help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printInsertHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing insert help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nInserts a triple, model, database or the results of a " +
-        "query into a model or database." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    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);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printInsertHelp()
-
-  /**
-   * Print the delete help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printDeleteHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing delete help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nDeletes a triple, model, database or the results of a " +
-        "query from a model or database." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    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);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printDeleteHelp()
-
-  /**
-   * Print the load help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printLoadHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing load help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nLoads the contents of a file into a model." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> load <http://foo.com/bar.rdf> into " +
-        "<rmi://localhost/foo#bar> ;" + eol);
-    helpMsg.append("  TQL> load local <file:/c:/data/foo.rdf> into " +
-        "<rmi://localhost/foo#foo> ;" + eol);
-    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);
-    helpMsg.append("'remote' refers to the file system on the server [default]" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printLoadHelp()
-
-  /**
-   * Print the backup help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printBackupHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing backup help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nPerforms a backup of a server or model." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append(
-        "  TQL> backup <rmi://localhost/server1> to remote <file:/tmp/server1backup> ;" + eol);
-    helpMsg.append(
-        "  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);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printBackupHelp()
-
-  /**
-   * Print the restore help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printRestoreHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing restore help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nRestores a server from a backup file. This will " +
-        "perform a union of the current contents of the server with the " +
-        "contents of the file" + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> restore <rmi://localhost/server1> from local " +
-        "<file:/tmp/server1backup> ;" + eol);
-    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);
-    helpMsg.append("'remote' refers to the file system on the server [default]" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printRestoreHelp()
-
-  /**
-   * Print the select help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printSelectHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing select help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nPerforms a query on a set of triples." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> select $subj $obj from " +
-        "<http://purl.org/dc/elements/1.1/> where $subj <rdfs:label> $obj ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printSelectHelp()
-
-  /**
-   * Print the commit help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printCommitHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing commit help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nCommits a transaction." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> commit ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printCommitHelp()
-
-  /**
-   * Print the rollback help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printRollbackHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing rollback help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nRolls back changes." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + eol + eol);
-    helpMsg.append("  TQL> rollback ;" + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printRollbackHelp()
-
-  /**
-   * Print the apply help message.
-   *
-   * @return A string containing the help message for the apply command
-   */
-  private static StringBuffer printApplyHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing apply help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nApplies a set of rules." + eol);
-    helpMsg.append("" + eol);
-    helpMsg.append("For example:" + 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("  TQL> apply <rmi://localhost/server1#krule> to <rmi://localhost/server1#camera> <rmi://localhost/server1#entailed>;" + eol);
-    return helpMsg;
-  }
-
-  // printApplyHelp()
-
-  /**
-   * Print the quit help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printQuitHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing quit  help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nQuits the iTQL interpreter." + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printQuitHelp()
-
-  /**
-   * Print the help help message.
-   *
-   * @return RETURNED VALUE TO DO
-   */
-  private static StringBuffer printHelpHelp() {
-
-    // log the command we're printing help for
-    log.debug("Printing help help screen");
-
-    // create the help message
-    StringBuffer helpMsg = new StringBuffer();
-    helpMsg.append("\nDisplays the help screen." + eol);
-
-    // return the help mesage
-    return helpMsg;
-  }
-
-  // printHelpHelp()
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/HelpPrinter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,738 @@
+/*
+ * 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 org.apache.log4j.Logger;
+
+// Automatically generated packages (SableCC)
+import org.mulgara.itql.analysis.DepthFirstAdapter;
+import org.mulgara.itql.node.*;
+
+/**
+ * Prints help for ITQL commands.
+ *
+ * @created 2001-09-10
+ *
+ * @author Tom Adams
+ *
+ * @version $Revision: 1.9 $
+ *
+ * @modified $Date: 2005/06/26 12:48:09 $ 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
+ *      Software Pty Ltd</a>
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class HelpPrinter {
+
+  //
+  // Constants
+  //
+
+  /**
+   * the category to log to
+   */
+  private final static Logger log = Logger.getLogger(HelpPrinter.class);
+
+  /**
+   * Get line separator.
+   */
+  private static final String eol = System.getProperty("line.separator");
+
+  /**
+   * message to print if a command does not have a help message
+   */
+  private final static String NO_HELP_MESSAGE =
+      eol + "No help exists for this command." + eol;
+
+  //
+  // Public API
+  //
+
+  /**
+   * Returns a help message for the given <code>command</code> (prefix).
+   *
+   * @param command the comand (prefix) to retrieve help for
+   * @return The Help value
+   */
+  public static String getHelp(PCommandPrefix command) {
+
+    // log that we're about to print the help
+    log.debug("Getting help for command - " + command);
+
+    // the help message
+    final StringBuffer helpMsg = new StringBuffer();
+
+    // delegate to the correct help printing method
+    command.apply(new DepthFirstAdapter() {
+
+      // we've got an empty help command (they want basic help)
+      public void caseAEmptyCommandPrefix(AEmptyCommandPrefix node) {
+
+        helpMsg.append(printDefaultHelp());
+      }
+
+      // caseAEmptyCommandPrefix()
+
+      /*
+             // NOTE: we need to hack the states in the grammar to get help on comments
+             // we've got a comment
+           public void caseACommentCommandPrefix(ACommentCommandPrefix node) {
+               helpMsg.append(printCommentHelp());
+             } // caseACommentCommandPrefix()
+       */
+
+      // we've got an alias
+      public void caseAAliasCommandPrefix(AAliasCommandPrefix node) {
+
+        helpMsg.append(printAliasHelp());
+      }
+
+      // caseAAliasCommandPrefix()
+      // we've got a create
+      public void caseACreateCommandPrefix(ACreateCommandPrefix node) {
+
+        helpMsg.append(printCreateHelp());
+      }
+
+      // caseACreateCommandPrefix()
+      // we've got a delete
+      public void caseADeleteCommandPrefix(ADeleteCommandPrefix node) {
+
+        helpMsg.append(printDeleteHelp());
+      }
+
+      // caseADeleteCommandPrefix()
+
+      /*
+             // NOTE: we don't currently support the directory command
+             // we've got directory
+           public void caseADirectoryCommandPrefix(ADirectoryCommandPrefix node) {
+               helpMsg.append(printDirectoryHelp());
+             } // caseADirectoryCommandPrefix()
+       */
+
+      // we've got a drop
+      public void caseADropCommandPrefix(ADropCommandPrefix node) {
+
+        helpMsg.append(printDropHelp());
+      }
+
+      // caseADropCommandPrefix()
+      // we've got an execute
+      public void caseAExecuteCommandPrefix(AExecuteCommandPrefix node) {
+
+        helpMsg.append(printExecuteHelp());
+      }
+
+      // caseAExecuteCommandPrefix()
+      // we've got a help
+      public void caseAHelpCommandPrefix(AHelpCommandPrefix node) {
+
+        helpMsg.append(printHelpHelp());
+      }
+
+      // caseAHelpCommandPrefix()
+      // we've got an insert
+      public void caseAInsertCommandPrefix(AInsertCommandPrefix node) {
+
+        helpMsg.append(printInsertHelp());
+      }
+
+      // caseAInsertCommandPrefix()
+      // we've got a load
+      public void caseALoadCommandPrefix(ALoadCommandPrefix node) {
+
+        helpMsg.append(printLoadHelp());
+      }
+
+      // caseALoadCommandPrefix()
+      // we've got a quit
+      public void caseAQuitCommandPrefix(AQuitCommandPrefix node) {
+
+        helpMsg.append(printQuitHelp());
+      }
+
+      // caseAQuitCommandPrefix()
+      // we've got a select
+      public void caseASelectCommandPrefix(ASelectCommandPrefix node) {
+
+        helpMsg.append(printSelectHelp());
+      }
+
+      // caseASelectCommandPrefix()
+      // we've got a set
+      public void caseASetCommandPrefix(ASetCommandPrefix node) {
+
+        helpMsg.append(printSetHelp());
+      }
+
+      // caseASetCommandPrefix()
+      // we've got an su
+      public void caseASuCommandPrefix(ASuCommandPrefix node) {
+
+        helpMsg.append(printSuHelp());
+      }
+
+      // caseASuCommandPrefix()
+      // we've got a backup
+      public void caseABackupCommandPrefix(ABackupCommandPrefix node) {
+
+        helpMsg.append(printBackupHelp());
+      }
+
+      // caseABackupCommandPrefix()
+      // we've got a restore
+      public void caseARestoreCommandPrefix(ARestoreCommandPrefix node) {
+
+        helpMsg.append(printRestoreHelp());
+      }
+
+      // caseARestoreCommandPrefix()
+      // we've got a commit
+      public void caseACommitCommandPrefix(ACommitCommandPrefix node) {
+
+        helpMsg.append(printCommitHelp());
+      }
+
+      // caseACommitCommandPrefix()
+      // we've got a rollback
+      public void caseARollbackCommandPrefix(ARollbackCommandPrefix node) {
+
+        helpMsg.append(printRollbackHelp());
+      }
+
+      // caseARollbackCommandPrefix()
+
+      // caseAApplyCommandPrefix()
+      public void caseAApplyCommandPrefix(AApplyCommandPrefix node) {
+
+        helpMsg.append(printApplyHelp());
+      }
+
+    });
+
+    // make sure that we got a message back (we may have implemented a new
+    // command but forgot to add a method to the visitor pattern above)
+    if (helpMsg.length() == 0) {
+
+      // append a "no help avaliable" message
+      helpMsg.append(NO_HELP_MESSAGE);
+    }
+
+    // end if
+    // log that we're returning help
+    log.debug("Returning help for command " + command);
+
+    // returning
+    return helpMsg.toString();
+  }
+
+  // getHelp()
+  //
+  // Internal methods
+  //
+
+  /**
+   * Print the default help message.
+   *
+   * @return the default help
+   */
+  private static StringBuffer printDefaultHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing default help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append(eol + "Valid commands are:" + eol + eol);
+
+    //helpMsg.append("  #       comment");
+    helpMsg.append("  su       authenticate a user" + eol);
+    helpMsg.append("  set      set a property" + eol);
+    helpMsg.append("  execute  execute an iTQL script" + eol);
+    helpMsg.append("  alias    define an alias" + eol);
+    helpMsg.append("  create   create a model" + eol);
+    helpMsg.append("  commit   commits a transaction" + eol);
+    helpMsg.append("  drop     drop an entire resource" + eol);
+    helpMsg.append("  insert   insert a set of triples" + eol);
+    helpMsg.append("  delete   delete a set of triples" + eol);
+    helpMsg.append("  load     load contents of a file          " + eol);
+    helpMsg.append("  backup   backup the contents of a server to a file" + eol);
+    helpMsg.append("  restore  restore a server from a backup file" + eol);
+    helpMsg.append("  rollback rolls back a transaction" + eol);
+    helpMsg.append("  select   perform a query" + eol);
+    helpMsg.append("  set      sets various options" + eol);
+    helpMsg.append("  apply    applies a set of rules" + eol);
+    helpMsg.append("  quit     end the ITQL session" + eol);
+    helpMsg.append("  help     display this help screen" + eol + eol);
+    helpMsg.append("You can also get detailed help on each command:" + eol + eol);
+    helpMsg.append("  $ help <command> ;" + eol + eol);
+    helpMsg.append("For example, to display help on the select command:" +
+        eol + eol);
+    helpMsg.append("  $ help select ;" + eol + eol);
+    helpMsg.append("Note. All commands must be terminated with \";\"." + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printDefaultHelp()
+
+  /**
+   * Print the su help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printSuHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing su help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nAuthenticates a user." + eol);
+    helpMsg.append(eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> su <ldap://bar.org> fred Fo0Bar ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printSuHelp()
+
+  /**
+   * Print the set help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printSetHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing ser help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append(eol + "Sets an iTQL interpreter option." + eol);
+    helpMsg.append(eol);
+    helpMsg.append("The following options are supported:" + eol + eol);
+
+    //helpMsg.append("  o echo - displays command results" + eol);
+    //helpMsg.append("  o statistics - " + eol);
+    //helpMsg.append("  o stoponerror - " + eol);
+    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("  TQL> set time on ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printSetHelp()
+
+  /**
+   * Print the execute help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printExecuteHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing execute help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nExecutes an iTQL script." + eol);
+    helpMsg.append(eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> execute " +
+        "<file:/usr/local/mulgara/sample/itql/loaddc.itql> ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printExecuteHelp()
+
+  /**
+   * Print the alias help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printAliasHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing alias help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nCreates an alias to a URL, model or database." + eol);
+    helpMsg.append(eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> alias <http://www.w3.org/2000/01/rdf-schema#> as " +
+        "rdfs ;" + eol);
+    helpMsg.append("  TQL> select $subj $obj from " +
+        "<http://purl.org/dc/elements/1.1/> where $subj <rdfs:label> $obj ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printAliasHelp()
+
+  /**
+   * Print the create help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printCreateHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing create help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append(eol + "Creates a new (empty) model." + eol);
+    helpMsg.append(eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> create <rmi://localhost/foo#bar> ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printCreateHelp()
+
+  /**
+   * Print the drop help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printDropHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing drop help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append(eol + "Drops a model." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> drop <rmi://localhost/foo#bar> ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printDropHelp()
+
+  /**
+   * Print the insert help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printInsertHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing insert help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nInserts a triple, model, database or the results of a " +
+        "query into a model or database." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    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);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printInsertHelp()
+
+  /**
+   * Print the delete help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printDeleteHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing delete help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nDeletes a triple, model, database or the results of a " +
+        "query from a model or database." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    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);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printDeleteHelp()
+
+  /**
+   * Print the load help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printLoadHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing load help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nLoads the contents of a file into a model." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> load <http://foo.com/bar.rdf> into " +
+        "<rmi://localhost/foo#bar> ;" + eol);
+    helpMsg.append("  TQL> load local <file:/c:/data/foo.rdf> into " +
+        "<rmi://localhost/foo#foo> ;" + eol);
+    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);
+    helpMsg.append("'remote' refers to the file system on the server [default]" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printLoadHelp()
+
+  /**
+   * Print the backup help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printBackupHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing backup help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nPerforms a backup of a server or model." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append(
+        "  TQL> backup <rmi://localhost/server1> to remote <file:/tmp/server1backup> ;" + eol);
+    helpMsg.append(
+        "  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);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printBackupHelp()
+
+  /**
+   * Print the restore help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printRestoreHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing restore help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nRestores a server from a backup file. This will " +
+        "perform a union of the current contents of the server with the " +
+        "contents of the file" + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> restore <rmi://localhost/server1> from local " +
+        "<file:/tmp/server1backup> ;" + eol);
+    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);
+    helpMsg.append("'remote' refers to the file system on the server [default]" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printRestoreHelp()
+
+  /**
+   * Print the select help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printSelectHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing select help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nPerforms a query on a set of triples." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> select $subj $obj from " +
+        "<http://purl.org/dc/elements/1.1/> where $subj <rdfs:label> $obj ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printSelectHelp()
+
+  /**
+   * Print the commit help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printCommitHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing commit help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nCommits a transaction." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> commit ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printCommitHelp()
+
+  /**
+   * Print the rollback help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printRollbackHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing rollback help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nRolls back changes." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + eol + eol);
+    helpMsg.append("  TQL> rollback ;" + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printRollbackHelp()
+
+  /**
+   * Print the apply help message.
+   *
+   * @return A string containing the help message for the apply command
+   */
+  private static StringBuffer printApplyHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing apply help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nApplies a set of rules." + eol);
+    helpMsg.append("" + eol);
+    helpMsg.append("For example:" + 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("  TQL> apply <rmi://localhost/server1#krule> to <rmi://localhost/server1#camera> <rmi://localhost/server1#entailed>;" + eol);
+    return helpMsg;
+  }
+
+  // printApplyHelp()
+
+  /**
+   * Print the quit help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printQuitHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing quit  help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nQuits the iTQL interpreter." + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printQuitHelp()
+
+  /**
+   * Print the help help message.
+   *
+   * @return RETURNED VALUE TO DO
+   */
+  private static StringBuffer printHelpHelp() {
+
+    // log the command we're printing help for
+    log.debug("Printing help help screen");
+
+    // create the help message
+    StringBuffer helpMsg = new StringBuffer();
+    helpMsg.append("\nDisplays the help screen." + eol);
+
+    // return the help mesage
+    return helpMsg;
+  }
+
+  // printHelpHelp()
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,1133 +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;
-
-// Java APIs
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.soap.SOAPException;
-
-import org.apache.axis.utils.DOM2Writer;
-import org.apache.axis.utils.XMLUtils;
-import org.apache.log4j.Logger;
-import org.jrdf.graph.BlankNode;
-import org.jrdf.graph.URIReference;
-import org.mulgara.connection.Connection;
-import org.mulgara.connection.ConnectionException;
-import org.mulgara.connection.ConnectionFactory;
-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.Export;
-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.server.Session;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-/**
- * iTQL Interpreter Bean.
- * <p>
- * This class provides a simple interface for the execution of iTQL queries.
- * </p>
- * <p>
- * Note. This class will be deprecated and is going away in favour of {@link org.mulgara.connection.MulgaraConnection}
- * based interfaces.
- * </p>
- *
- * @created 2001-Aug-30
- * @author Tate Jones
- * @author Ben Warren
- * @author Tom Adams
- * @version $Revision: 1.11 $
- * @modified $Date: 2005/04/04 11:30:11 $ by $Author: tomadams $
- * @copyright &copy;2001-2004 <a href="http://www.tucanatech.com/">Tucana Technology, Inc</a>
- * @copyright &copy;2005 <a href="mailto:tomjadams at gmail.com">Tom Adams</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlInterpreterBean {
-
-  /** The logger */
-  private final static Logger log = Logger.getLogger(ItqlInterpreterBean.class.getName());
-
-  /** 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#";
-  
-  /** 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 TQL interpreter.
-   */
-  public ItqlInterpreterBean() {
-    if (log.isInfoEnabled()) log.info("Created an ItqlInterpreterBean");
-  }
-
-  /**
-   * @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");
-    }
-    legacySession = session;
-    interpreter.preSeedSession(session);
-    interpreter.setSecurityDomain(securityDomain);
-  }
-
-  // executeQueryToMap()
-
-  /**
-   * Splits a query containing multiple queries into an array of single queries.
-   *
-   * @param multiQuery PARAMETER TO DO
-   * @return An array of query strings which include the ending ';' charater.
-   */
-  public static String[] splitQuery(String multiQuery) {
-
-    List<String> singleQueryList = new ArrayList<String>();
-
-    // Inside a URI?
-    boolean INSIDE_URI = false;
-
-    // Inside a text literal?
-    boolean INSIDE_TEXT = false;
-
-    // Start index for next single query
-    int startIndex = 0;
-
-    if (log.isDebugEnabled()) log.debug("About to break up query: " + multiQuery);
-
-    multiQuery = multiQuery.trim();
-
-    // Iterate along the multi query and strip out the single queries.
-    for (int lineIndex = 0; lineIndex < multiQuery.length(); lineIndex++) {
-
-      char currentChar = multiQuery.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 (!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();
-            startIndex = lineIndex + 1;
-            singleQueryList.add(singleQuery);
-            if (log.isDebugEnabled()) log.debug("Found single query: " + singleQuery);
-          }
-          break;
-
-        default:
-      }
-    }
-
-    // Lasy query is not terminated with a ';'
-    if (startIndex < multiQuery.length()) {
-      singleQueryList.add(multiQuery.substring(startIndex, multiQuery.length()));
-    }
-
-    return singleQueryList.toArray(new String[singleQueryList.size()]);
-  }
-
-  /**
-   * Returns 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() {
-    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,
-   * or <code>null</code> if it was not possible to create a session for the URI.
-   */
-  public Session getSession(URI serverURI) {
-    try {
-      return interpreter.establishConnection(serverURI).getSession();
-    } catch (Exception e) {
-      log.error("Unable to get session for: " + serverURI, e);
-      return null;
-    }
-  }
-
-
-  /**
-   * Returns the aliases associated with this bean.
-   *
-   * @return the alias namespace map associated with this bean.
-   */
-  @SuppressWarnings("deprecation")
-  public Map<String,URI> getAliasMap() {
-    return this.interpreter.getAliasesInUse();
-  }
-
-  /**
-   * Closes the session underlying this bean.
-   */
-  public void close() {
-    interpreter.close();
-  }
-
-  //
-  // Public API
-  //
-
-  /**
-   * Begin a new transaction by setting the autocommit off
-   *
-   * @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()) log.debug("Begin transaction for :" + name);
-
-    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);
-    }
-  }
-
-  /**
-   * Commit a new transaction by setting the autocommit on
-   *
-   * @param name the name of the transaction ( debug purposes only ) *
-   * @throws QueryException Unable to commit one of the connections.
-   */
-  @SuppressWarnings("deprecation")
-  public void commit(String name) throws QueryException {
-
-    if (log.isDebugEnabled()) log.debug("Commit transaction for :" + name);
-
-    interpreter.commitAll();
-  }
-
-
-  /**
-   * Rollback an existing transaction
-   *
-   * @param name the name of the transaction ( debug purposes only ) *
-   * @throws QueryException Unable to rollback one of the connections
-   */
-  @SuppressWarnings("deprecation")
-  public void rollback(String name) throws QueryException {
-
-    log.warn("Rollback transaction for :" + name);
-
-    interpreter.rollbackAll();
-  }
-
-  /**
-   * Answer TQL queries.
-   *
-   * @param queryString PARAMETER TO DO
-   * @return the answer DOM to the TQL query
-   * @throws Exception EXCEPTION TO DO
-   */
-  public Element execute(String queryString) throws Exception {
-    try {
-      //DocumentBuilder xdb = XMLParserUtils.getXMLDocBuilder();
-      //Document doc = xdb.newDocument();
-      Document doc = XMLUtils.newDocument();
-
-      Element answerDom = doc.createElementNS(TQL_NS, "answer");
-      answerDom.setAttribute("xmlns", TQL_NS);
-
-      if (log.isDebugEnabled()) {
-        log.debug("Received a TQL query : " + queryString);
-      }
-
-      String[] queries = splitQuery(queryString);
-
-      for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
-        String singleQuery = queries[queryIndex];
-
-        // Attach the answer
-        Element query = (Element) answerDom.appendChild(doc.createElementNS(TQL_NS, "query"));
-
-        // Resolve the query
-        if (log.isDebugEnabled()) {
-          log.debug("Executing query : " + singleQuery);
-        }
-
-        executeCommand(singleQuery);
-
-        Answer answer = null;
-        try {
-          answer = this.interpreter.getLastAnswer();
-
-          if ((answer == null) || answer.isUnconstrained()) {
-            if (this.interpreter.getLastException() == null) {
-              //Not an error, but a message does exist
-              Element message =
-                  (Element)query.appendChild(doc.createElementNS(TQL_NS, "message"));
-              message.appendChild(doc.createTextNode(interpreter.getLastMessage()));
-
-              if (log.isDebugEnabled()) {
-                log.debug("Attached last message: " + interpreter.getLastMessage());
-              }
-            } else {
-              //Error has occurred at the interpreter
-              //Generate a SOAP fault
-              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 - " +
-                  ItqlUtil.getCause(interpreter.getLastException(), 0));
-              // TODO: consider adding + EOL + "Query: [" + singleQuery + "]");
-              // though must first consider impact on clients
-            }
-            // Ensure answer is null.
-            answer = null;
-          } else {
-            log.debug("Building XML result set");
-            appendSolution(answer, query);
-            log.debug("Attached answer text");
-          }
-        } finally {
-          if (answer != null) {
-            answer.close();
-          }
-        }
-      }
-
-      // Send the answer back to the caller
-      return answerDom;
-    } catch (Exception e) {
-      log.error("Failed to execute query", e);
-      throw e;
-    }
-  }
-
-
-  /**
-   * Answer TQL queries.
-   *
-   * @param queryString A query to execute
-   * @return the answer String to the TQL query
-   * @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);
-
-    return result;
-  }
-
-
-  /**
-   * Executes a semicolon delimited string of queries. <p>
-   *
-   * This method allows you to execute mulitple queries at once by specifying a
-   * string of the following form: </p> <pre>
-   * String queryString = "select $s $p $o from <rmi://machine/server1#model> " +
-   *     "where $s $p $o;";
-   * queryString += "select $s $p $o from <rmi://machine2/server1#model> " +
-   *     "where $s $p $o;";
-   * </pre> <p>
-   *
-   * The ordering of the result list will correspond to the ordering of the
-   * queries in the input string. </p> <p>
-   *
-   * Note. Two different return types will be contained in the returned list. An
-   * {@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
-   * @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<Object> executeQueryToList(String queryString) {
-    return executeQueryToList(queryString, false);
-  }
-
-
-  /**
-   * Executes a semicolon delimited string of queries. <p>
-   *
-   * This method allows you to execute mulitple queries at once by specifying a
-   * string of the following form: </p> <pre>
-   * String queryString = "select $s $p $o from <rmi://machine/server1#model> " +
-   *     "where $s $p $o;";
-   * queryString += "select $s $p $o from <rmi://machine2/server1#model> " +
-   *     "where $s $p $o;";
-   * </pre> <p>
-   *
-   * The ordering of the result list will correspond to the ordering of the
-   * queries in the input string. </p> <p>
-   *
-   * Note. Two different return types will be contained in the returned list. An
-   * {@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 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
-   */
-  public List<Object> executeQueryToList(String queryString, boolean keepExceptions) {
-
-    List<Object> answers = new ArrayList<Object>();
-
-    if (log.isDebugEnabled()) log.debug("Received a TQL query : " + queryString);
-
-    String[] queries = splitQuery(queryString);
-
-    for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
-
-      String singleQuery = queries[queryIndex];
-
-      // Resolve the query
-      if (log.isDebugEnabled()) log.debug("Executing query : " + singleQuery);
-
-      // execute it
-      answers.add(this.executeQueryToNiceResult(singleQuery, keepExceptions));
-    }
-
-    // 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>
-   *
-   * The <var>queries</var> is a map of keys ({@link java.lang.Object}s) to
-   * queries ({@link java.lang.String}s). Each query will be excuted (in the
-   * order in which <var>queries</var> 's map implementation {@link
-   * java.util.Map#keySet()}'s {@link java.util.Set#iterator()} returns keys)
-   * and the results added to the returned map, keyed on the same key as the
-   * original query. </p> <p>
-   *
-   * For example: </p> <pre>
-   * // create the queries
-   * URI title = new URI("http://www.foo.com/title");
-   * String titleQuery = "select $s $p $o from <rmi://machine/server1#model> " +
-   *     "where $s $p $o;";
-   * URI date = new URI("http://www.foo.com/date");
-   * String dateQuery = "select $s $p $o from <rmi://machine2/server1#model> " +
-   *     "where $s $p $o;";
-   *
-   * // add them to the map
-   * HashMap queries = new HashMap();
-   * queries.put(title, titleQuery);
-   * queries.put(date, dateQuery);
-   *
-   * // execute them
-   * ItqlInterpreterBean itb = new ItqlInterpreterBean();
-   * HashMap answers = itb.executeQueryToMap(queries);
-   *
-   * // get the answers
-   * Answer titleAnswer = answers.get(title);
-   * Answer dateAnswer = answers.get(date);
-   * </pre> <p>
-   *
-   * Note. Each answer will be either a {@link org.mulgara.query.Answer} or a
-   * {@link java.lang.String} (error) message. </p>
-   *
-   * @param queries a map of keys to queries to be executed
-   * @return a map of answers and error messages
-   */
-  public Map<Object,Object> executeQueryToMap(Map<Object,String> queries) {
-
-    // create the answer map
-    HashMap<Object,Object> answers = new HashMap<Object,Object>();
-
-    // iterate over the queries
-    for (Iterator<Object> keyIter = queries.keySet().iterator(); keyIter.hasNext(); ) {
-
-      // get the key and the query
-      Object key = keyIter.next();
-      String query = queries.get(key);
-
-      // log the query we're executing
-      if (log.isDebugEnabled()) log.debug("Executing " + key + " -> " + query);
-
-      // execute the query
-      answers.put(key, this.executeQueryToNiceResult(query, false));
-    }
-
-    // return the answers
-    return answers;
-  }
-
-
-  /**
-   * Builds a {@link org.mulgara.query.Query} from the given <var>query</var>.
-   *
-   * @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
-   * @throws LexerException if <var>query</var> can't be tokenized
-   * @throws ParserException if the <var>query</var> is not syntactically
-   *      correct
-   */
-  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;
-  }
-
-
-  /**
-   * Execute an iTQL &quot;update&quot; statement that returns no results.
-   * <p>
-   *   This method should be used only for commands that return no results
-   *   such as <code>INSERT</code> and <code>ALIAS</code>.
-   * </p>
-   *
-   * @param itql The statement to execute.
-   *
-   * @throws ItqlInterpreterException if the statement fails or the command
-   *   executed returned results.
-   */
-  public void executeUpdate(String itql) throws ItqlInterpreterException {
-
-    try {
-      executeCommand(itql);
-    } catch (Exception e) {
-      throw new ItqlInterpreterException(e);
-    }
-
-    Exception e = interpreter.getLastException();
-    ItqlInterpreterException exception = (e == null) ? null : new ItqlInterpreterException(e);
-    Answer answer = interpreter.getLastAnswer();
-
-    if (answer != null) {
-
-      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;
-  }
-
-
-  /**
-   * Returns true if a quit command has been entered.
-   *
-   * @return true if a quit command has been entered
-   */
-  public boolean isQuitRequested() {
-    return quit;
-  }
-
-
-  /**
-   * Returns the {@linkplain TqlAutoInterpreter#getLastMessage last message} of
-   * the interpreter.
-   *
-   * @return the results of the last command execution, null if the command did
-   *      not set any message
-   *
-   * @see TqlAutoInterpreter#getLastMessage()
-   */
-  public String getLastMessage() {
-    return interpreter.getLastMessage();
-  }
-
-
-  /**
-   * Returns the {@linkplain TqlAutoInterpreter#getLastException last error} of
-   * the interpreter.
-   *
-   * @return the results of the last command execution, null if the command did
-   *      not set any message
-   *
-   * @see TqlAutoInterpreter#getLastException()
-   */
-  public ItqlInterpreterException getLastError() {
-    return new ItqlInterpreterException(interpreter.getLastException());
-  }
-
-
-  /**
-   * Execute an ITQL query and return an answer.
-   *
-   * @param itql The query to execute.
-   * @return The answer to the query.
-   * @throws ItqlInterpreterException if the query fails.
-   */
-  public Answer executeQuery(String itql) throws ItqlInterpreterException {
-    try {
-      executeCommand(itql);
-    } catch (Exception e) {
-      throw new ItqlInterpreterException(e);
-    }
-
-    Exception exception = interpreter.getLastException();
-    if (exception != null) throw new ItqlInterpreterException(exception);
-
-    return interpreter.getLastAnswer();
-  }
-
-
-  /**
-   * Load the contents of a local file into a database/model.
-   * <p>
-   *   The method assumes the source to be RDF/XML if an .rdf extension can
-   *   not be found.  A .n3 extension assume n3 triples.
-   * </p>
-   * <p>
-   *   Note. <var>destinationURI</var> must be a valid URI, and does not include
-   *   the angle brackets (&lt; and &gt;) used to delimit URLs in iTQL.
-   * </p>
-   *
-   * @param sourceFile  a local file containing the source data
-   * @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 or the file does not exist
-   * on the local file system.
-   */
-  public long load(File sourceFile, URI destinationURI) throws QueryException {
-    long numberOfStatements = 0;
-
-    // check for the local file
-    if (!sourceFile.exists()) {
-      throw new QueryException(sourceFile+" does not exist on the local file system");
-    }
-    try {
-      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;
-   }
-
-
-  /**
-   * Backup all the data on the specified server to a client local file.
-   * The database is not changed by this method.
-   *
-   * @param sourceURI The URI of the server 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.
-   */
-  @SuppressWarnings("deprecation")
-  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 (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.
-   *
-   * @param sourceURI The URI of the server to backup.
-   * @param outputStream The stream to receive the contents
-   * @throws QueryException if the backup cannot be completed.
-   */
-  @SuppressWarnings("deprecation")
-  public void backup(URI sourceURI, OutputStream outputStream) throws QueryException {
-    Backup backup = new Backup(sourceURI, null, true);
-    backup.setOverrideOutputStream(outputStream);
-    try {
-      backup.execute(interpreter.establishConnection(backup.getServerURI()));
-    } catch (ConnectionException e) {
-      throw new QueryException("Unable to establish connection to: " + backup.getServerURI(), e);
-    }
-  }
-  
-  
-  /**
-   * Export the data in the specified graph to a client local file.
-   * The database is not changed by this method.
-   *
-   * @param graphURI The URI of the graph to export.
-   * @param destinationFile an non-existent file on the local file system to
-   * receive the export contents.
-   * @throws QueryException if the export cannot be completed.
-   */
-  public void export(URI graphURI, File destinationFile) throws QueryException {
-    Export export = new Export(graphURI, destinationFile.toURI(), true);
-    try {
-      export.execute(interpreter.establishConnection(export.getServerURI()));
-    } catch (ConnectionException e) {
-      throw new QueryException("Unable to establish connection to: " + export.getServerURI(), e);
-    }
-  }
-  
-  
-  /**
-   * Export the data in the specified graph to an output stream.
-   * The database is not changed by this method.
-   *
-   * @param graphURI The URI of the graph to export.
-   * @param outputStream The stream to receive the contents
-   * @throws QueryException if the export cannot be completed.
-   */
-  public void export(URI graphURI, OutputStream outputStream) throws QueryException {
-    Export export = new Export(graphURI, outputStream);
-    try {
-      export.execute(interpreter.establishConnection(export.getServerURI()));
-    } catch (ConnectionException e) {
-      throw new QueryException("Unable to establish connection to: " + export.getServerURI(), e);
-    }
-  }
-
-
-  /**
-   * Load the contents of an InputStream into a database/model.  The method assumes
-   * the source to be RDF/XML.
-   * <p>
-   *   Note. <var>destinationURI</var> must be a valid URI, and does not include
-   *   the angle brackets (&lt; and &gt;) used to delimit URLs in iTQL.
-   * </p>
-   *
-   * @param inputStream a locally supplied inputstream.
-   * @param destinationURI destination model for the source data
-   * @return number of rows inserted into the destination model
-   */
-  public long load(InputStream inputStream, URI destinationURI) throws QueryException {
-    return load(inputStream, null, destinationURI);
-  }
-
-
-  /**
-   * Load the contents of an InputStream or a URI into a database/model.
-   * <p>
-   *   Note. <var>destinationURI</var> must be a valid URI, and does not include
-   *   the angle brackets (&lt; and &gt;) used to delimit URLs in iTQL.
-   * </p>
-   *
-   * @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 {
-    long numberOfStatements = 0;
-    try {
-      Load loadCmd = new Load(sourceURI, destinationURI, true);
-      loadCmd.setOverrideInputStream(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
-   * content and the content of the backup file when this method returns.
-   *
-   * @param inputStream An input 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 {
-     restore(inputStream, serverURI, null);
-  }
-
-
-  /**
-   * 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.
-   */
-  @SuppressWarnings("deprecation")
-  public void restore(InputStream inputStream, URI serverURI, URI sourceURI) throws QueryException {
-    try {
-      Restore restoreCmd = new Restore(sourceURI, serverURI, true);
-      restoreCmd.setOverrideInputStream(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);
-    }
-  }
-
-
-  /**
-   * @param answer the answer to convert into XML
-   * @param parent the XML element to add the query solutions to
-   * @throws QueryException if the solutions can't be added
-   */
-  private void appendSolution(Answer answer, Element parent)
-    throws QueryException {
-
-    try {
-      Document doc = parent.getOwnerDocument();
-
-      Element VARIABLES = doc.createElementNS(TQL_NS, "variables");
-
-      // Add the variable list
-      Element variables = (Element) parent.appendChild(VARIABLES);
-
-      for (int column = 0; column < answer.getVariables().length; column++) {
-        variables.appendChild(doc.createElement(answer.getVariables()[column].getName()));
-      }
-
-      // Add any solutions
-      answer.beforeFirst();
-
-      while (answer.next()) {
-
-        Element solution = doc.createElementNS(TQL_NS, "solution");
-
-        for (int column = 0; column < answer.getVariables().length; column++) {
-
-          Object object = answer.getObject(column);
-
-          // If the node is null, don't add a tag at all
-          if (object == null) continue;
-
-          // Otherwise, add a tag for the node
-          Element variable =
-              (Element) solution.appendChild(doc.createElementNS(TQL_NS,
-              answer.getVariables()[column].getName()));
-
-          if (object instanceof Answer) {
-
-            Answer tmpAnswer = (Answer) object;
-            try {
-              appendSolution(tmpAnswer, variable);
-            } finally {
-              tmpAnswer.close();
-            }
-
-          } else if (object instanceof LiteralImpl) {
-
-            LiteralImpl literal = (LiteralImpl)object;
-            if (literal.getDatatypeURI() != null) {
-              variable.setAttribute("datatype", literal.getDatatypeURI().toString());
-            }
-            String language = literal.getLanguage();
-            if (language != null && language.length() != 0) {
-              variable.setAttribute("language", language);
-            }
-            variable.appendChild(doc.createTextNode(literal.getLexicalForm()));
-          } else if (object instanceof URIReference) {
-
-            variable.setAttribute("resource", ((URIReference)object).getURI().toString());
-          } else if (object instanceof BlankNode) {
-
-            variable.setAttribute("blank-node", object.toString());
-          } else {
-            throw new AssertionError("Unknown RDFNode type: " + object.getClass());
-          }
-        }
-
-        parent.appendChild(solution);
-      }
-    } catch (TuplesException e) {
-      throw new QueryException("Couldn't build query", e);
-    }
-  }
-
-
-  //
-  // Internal methods
-  //
-
-  /**
-   * Executes the <var>query</var> , returning a &quot;nice&quot; result. <p>
-   *
-   * The result is either a {@link java.lang.String} or a {@link
-   * org.mulgara.query.Answer}. Any exceptions are logged, gobbled and return
-   * as a {@link java.lang.String}. </p>
-   *
-   * @param query the query to execute
-   * @param keepExceptions keep exceptions, don't convert to a message.
-   * @return the result of the query in a &quot;nice&quot; format
-   */
-  private Object executeQueryToNiceResult(String query, boolean keepExceptions) {
-
-    // create the result
-    Object result = null;
-
-    try {
-
-      // get the answer to the 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.getLastException() != null) {
-
-          // error has occurred at the interpreter
-          if (log.isDebugEnabled()) {
-            log.debug("Adding query error to map - " + this.interpreter.getLastException());
-          }
-
-          // end if
-          // set this as the answer
-          if (keepExceptions) {
-            result = this.interpreter.getLastException();
-          } else {
-            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());
-          }
-
-          // end if
-          // set this as the answer
-          result = interpreter.getLastMessage();
-        }
-
-        // end if
-      }
-
-      // end if
-    } catch (Exception e) {
-
-      if (keepExceptions) {
-        result = e;
-      } else {
-
-        // get root cause exception
-        Throwable cause = e.getCause();
-        Throwable lastCause = e;
-
-        while (cause != null) {
-          lastCause = cause;
-          cause = cause.getCause();
-        }
-
-        // end while
-        // format the exception message
-        String exceptionMessage = lastCause.getMessage();
-
-        if (exceptionMessage == null) {
-          exceptionMessage = lastCause.toString();
-        }
-
-        // end if
-        // turn it into a pretty string
-        exceptionMessage = "Query Error: " + exceptionMessage;
-
-        // log the message
-        if (log.isDebugEnabled()) {
-          log.debug(exceptionMessage);
-        }
-
-        // end if
-        // add the exception message to the answers
-        result = exceptionMessage;
-
-        // log full stack trace
-        StringWriter stringWriter = new StringWriter();
-        PrintWriter printWriter = new PrintWriter(stringWriter);
-        e.printStackTrace(printWriter);
-        printWriter.flush();
-        stringWriter.flush();
-
-        log.error("Error while processing query: '" + query + "' " + EOL +
-            stringWriter.getBuffer().toString());
-      }
-    }
-
-    return result;
-  }
-
-
-  /**
-    * 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) {
-    // Do nothing
-  }
-
-
-  /**
-   * Sets the aliases associated with this bean.
-   *
-   * @param aliasMap the alias map associated with this bean
-   */
-  @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.clearLastException();
-  }
-
- /**
-  * Ensures all resources are closed at GC.
-  * Especially important if this object is in a servlet
-  * 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);
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBean.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,1133 @@
+/*
+ * 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;
+
+// Java APIs
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.soap.SOAPException;
+
+import org.apache.axis.utils.DOM2Writer;
+import org.apache.axis.utils.XMLUtils;
+import org.apache.log4j.Logger;
+import org.jrdf.graph.BlankNode;
+import org.jrdf.graph.URIReference;
+import org.mulgara.connection.Connection;
+import org.mulgara.connection.ConnectionException;
+import org.mulgara.connection.ConnectionFactory;
+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.Export;
+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.server.Session;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * iTQL Interpreter Bean.
+ * <p>
+ * This class provides a simple interface for the execution of iTQL queries.
+ * </p>
+ * <p>
+ * Note. This class will be deprecated and is going away in favour of {@link org.mulgara.connection.MulgaraConnection}
+ * based interfaces.
+ * </p>
+ *
+ * @created 2001-Aug-30
+ * @author Tate Jones
+ * @author Ben Warren
+ * @author Tom Adams
+ * @version $Revision: 1.11 $
+ * @modified $Date: 2005/04/04 11:30:11 $ by $Author: tomadams $
+ * @copyright &copy;2001-2004 <a href="http://www.tucanatech.com/">Tucana Technology, Inc</a>
+ * @copyright &copy;2005 <a href="mailto:tomjadams at gmail.com">Tom Adams</a>
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class ItqlInterpreterBean {
+
+  /** The logger */
+  private final static Logger log = Logger.getLogger(ItqlInterpreterBean.class.getName());
+
+  /** 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#";
+  
+  /** 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 TQL interpreter.
+   */
+  public ItqlInterpreterBean() {
+    if (log.isInfoEnabled()) log.info("Created an ItqlInterpreterBean");
+  }
+
+  /**
+   * @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");
+    }
+    legacySession = session;
+    interpreter.preSeedSession(session);
+    interpreter.setSecurityDomain(securityDomain);
+  }
+
+  // executeQueryToMap()
+
+  /**
+   * Splits a query containing multiple queries into an array of single queries.
+   *
+   * @param multiQuery PARAMETER TO DO
+   * @return An array of query strings which include the ending ';' charater.
+   */
+  public static String[] splitQuery(String multiQuery) {
+
+    List<String> singleQueryList = new ArrayList<String>();
+
+    // Inside a URI?
+    boolean INSIDE_URI = false;
+
+    // Inside a text literal?
+    boolean INSIDE_TEXT = false;
+
+    // Start index for next single query
+    int startIndex = 0;
+
+    if (log.isDebugEnabled()) log.debug("About to break up query: " + multiQuery);
+
+    multiQuery = multiQuery.trim();
+
+    // Iterate along the multi query and strip out the single queries.
+    for (int lineIndex = 0; lineIndex < multiQuery.length(); lineIndex++) {
+
+      char currentChar = multiQuery.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 (!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();
+            startIndex = lineIndex + 1;
+            singleQueryList.add(singleQuery);
+            if (log.isDebugEnabled()) log.debug("Found single query: " + singleQuery);
+          }
+          break;
+
+        default:
+      }
+    }
+
+    // Lasy query is not terminated with a ';'
+    if (startIndex < multiQuery.length()) {
+      singleQueryList.add(multiQuery.substring(startIndex, multiQuery.length()));
+    }
+
+    return singleQueryList.toArray(new String[singleQueryList.size()]);
+  }
+
+  /**
+   * Returns 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() {
+    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,
+   * or <code>null</code> if it was not possible to create a session for the URI.
+   */
+  public Session getSession(URI serverURI) {
+    try {
+      return interpreter.establishConnection(serverURI).getSession();
+    } catch (Exception e) {
+      log.error("Unable to get session for: " + serverURI, e);
+      return null;
+    }
+  }
+
+
+  /**
+   * Returns the aliases associated with this bean.
+   *
+   * @return the alias namespace map associated with this bean.
+   */
+  @SuppressWarnings("deprecation")
+  public Map<String,URI> getAliasMap() {
+    return this.interpreter.getAliasesInUse();
+  }
+
+  /**
+   * Closes the session underlying this bean.
+   */
+  public void close() {
+    interpreter.close();
+  }
+
+  //
+  // Public API
+  //
+
+  /**
+   * Begin a new transaction by setting the autocommit off
+   *
+   * @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()) log.debug("Begin transaction for :" + name);
+
+    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);
+    }
+  }
+
+  /**
+   * Commit a new transaction by setting the autocommit on
+   *
+   * @param name the name of the transaction ( debug purposes only ) *
+   * @throws QueryException Unable to commit one of the connections.
+   */
+  @SuppressWarnings("deprecation")
+  public void commit(String name) throws QueryException {
+
+    if (log.isDebugEnabled()) log.debug("Commit transaction for :" + name);
+
+    interpreter.commitAll();
+  }
+
+
+  /**
+   * Rollback an existing transaction
+   *
+   * @param name the name of the transaction ( debug purposes only ) *
+   * @throws QueryException Unable to rollback one of the connections
+   */
+  @SuppressWarnings("deprecation")
+  public void rollback(String name) throws QueryException {
+
+    log.warn("Rollback transaction for :" + name);
+
+    interpreter.rollbackAll();
+  }
+
+  /**
+   * Answer TQL queries.
+   *
+   * @param queryString PARAMETER TO DO
+   * @return the answer DOM to the TQL query
+   * @throws Exception EXCEPTION TO DO
+   */
+  public Element execute(String queryString) throws Exception {
+    try {
+      //DocumentBuilder xdb = XMLParserUtils.getXMLDocBuilder();
+      //Document doc = xdb.newDocument();
+      Document doc = XMLUtils.newDocument();
+
+      Element answerDom = doc.createElementNS(TQL_NS, "answer");
+      answerDom.setAttribute("xmlns", TQL_NS);
+
+      if (log.isDebugEnabled()) {
+        log.debug("Received a TQL query : " + queryString);
+      }
+
+      String[] queries = splitQuery(queryString);
+
+      for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
+        String singleQuery = queries[queryIndex];
+
+        // Attach the answer
+        Element query = (Element) answerDom.appendChild(doc.createElementNS(TQL_NS, "query"));
+
+        // Resolve the query
+        if (log.isDebugEnabled()) {
+          log.debug("Executing query : " + singleQuery);
+        }
+
+        executeCommand(singleQuery);
+
+        Answer answer = null;
+        try {
+          answer = this.interpreter.getLastAnswer();
+
+          if ((answer == null) || answer.isUnconstrained()) {
+            if (this.interpreter.getLastException() == null) {
+              //Not an error, but a message does exist
+              Element message =
+                  (Element)query.appendChild(doc.createElementNS(TQL_NS, "message"));
+              message.appendChild(doc.createTextNode(interpreter.getLastMessage()));
+
+              if (log.isDebugEnabled()) {
+                log.debug("Attached last message: " + interpreter.getLastMessage());
+              }
+            } else {
+              //Error has occurred at the interpreter
+              //Generate a SOAP fault
+              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 - " +
+                  ItqlUtil.getCause(interpreter.getLastException(), 0));
+              // TODO: consider adding + EOL + "Query: [" + singleQuery + "]");
+              // though must first consider impact on clients
+            }
+            // Ensure answer is null.
+            answer = null;
+          } else {
+            log.debug("Building XML result set");
+            appendSolution(answer, query);
+            log.debug("Attached answer text");
+          }
+        } finally {
+          if (answer != null) {
+            answer.close();
+          }
+        }
+      }
+
+      // Send the answer back to the caller
+      return answerDom;
+    } catch (Exception e) {
+      log.error("Failed to execute query", e);
+      throw e;
+    }
+  }
+
+
+  /**
+   * Answer TQL queries.
+   *
+   * @param queryString A query to execute
+   * @return the answer String to the TQL query
+   * @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);
+
+    return result;
+  }
+
+
+  /**
+   * Executes a semicolon delimited string of queries. <p>
+   *
+   * This method allows you to execute mulitple queries at once by specifying a
+   * string of the following form: </p> <pre>
+   * String queryString = "select $s $p $o from <rmi://machine/server1#model> " +
+   *     "where $s $p $o;";
+   * queryString += "select $s $p $o from <rmi://machine2/server1#model> " +
+   *     "where $s $p $o;";
+   * </pre> <p>
+   *
+   * The ordering of the result list will correspond to the ordering of the
+   * queries in the input string. </p> <p>
+   *
+   * Note. Two different return types will be contained in the returned list. An
+   * {@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
+   * @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<Object> executeQueryToList(String queryString) {
+    return executeQueryToList(queryString, false);
+  }
+
+
+  /**
+   * Executes a semicolon delimited string of queries. <p>
+   *
+   * This method allows you to execute mulitple queries at once by specifying a
+   * string of the following form: </p> <pre>
+   * String queryString = "select $s $p $o from <rmi://machine/server1#model> " +
+   *     "where $s $p $o;";
+   * queryString += "select $s $p $o from <rmi://machine2/server1#model> " +
+   *     "where $s $p $o;";
+   * </pre> <p>
+   *
+   * The ordering of the result list will correspond to the ordering of the
+   * queries in the input string. </p> <p>
+   *
+   * Note. Two different return types will be contained in the returned list. An
+   * {@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 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
+   */
+  public List<Object> executeQueryToList(String queryString, boolean keepExceptions) {
+
+    List<Object> answers = new ArrayList<Object>();
+
+    if (log.isDebugEnabled()) log.debug("Received a TQL query : " + queryString);
+
+    String[] queries = splitQuery(queryString);
+
+    for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
+
+      String singleQuery = queries[queryIndex];
+
+      // Resolve the query
+      if (log.isDebugEnabled()) log.debug("Executing query : " + singleQuery);
+
+      // execute it
+      answers.add(this.executeQueryToNiceResult(singleQuery, keepExceptions));
+    }
+
+    // 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>
+   *
+   * The <var>queries</var> is a map of keys ({@link java.lang.Object}s) to
+   * queries ({@link java.lang.String}s). Each query will be excuted (in the
+   * order in which <var>queries</var> 's map implementation {@link
+   * java.util.Map#keySet()}'s {@link java.util.Set#iterator()} returns keys)
+   * and the results added to the returned map, keyed on the same key as the
+   * original query. </p> <p>
+   *
+   * For example: </p> <pre>
+   * // create the queries
+   * URI title = new URI("http://www.foo.com/title");
+   * String titleQuery = "select $s $p $o from <rmi://machine/server1#model> " +
+   *     "where $s $p $o;";
+   * URI date = new URI("http://www.foo.com/date");
+   * String dateQuery = "select $s $p $o from <rmi://machine2/server1#model> " +
+   *     "where $s $p $o;";
+   *
+   * // add them to the map
+   * HashMap queries = new HashMap();
+   * queries.put(title, titleQuery);
+   * queries.put(date, dateQuery);
+   *
+   * // execute them
+   * ItqlInterpreterBean itb = new ItqlInterpreterBean();
+   * HashMap answers = itb.executeQueryToMap(queries);
+   *
+   * // get the answers
+   * Answer titleAnswer = answers.get(title);
+   * Answer dateAnswer = answers.get(date);
+   * </pre> <p>
+   *
+   * Note. Each answer will be either a {@link org.mulgara.query.Answer} or a
+   * {@link java.lang.String} (error) message. </p>
+   *
+   * @param queries a map of keys to queries to be executed
+   * @return a map of answers and error messages
+   */
+  public Map<Object,Object> executeQueryToMap(Map<Object,String> queries) {
+
+    // create the answer map
+    HashMap<Object,Object> answers = new HashMap<Object,Object>();
+
+    // iterate over the queries
+    for (Iterator<Object> keyIter = queries.keySet().iterator(); keyIter.hasNext(); ) {
+
+      // get the key and the query
+      Object key = keyIter.next();
+      String query = queries.get(key);
+
+      // log the query we're executing
+      if (log.isDebugEnabled()) log.debug("Executing " + key + " -> " + query);
+
+      // execute the query
+      answers.put(key, this.executeQueryToNiceResult(query, false));
+    }
+
+    // return the answers
+    return answers;
+  }
+
+
+  /**
+   * Builds a {@link org.mulgara.query.Query} from the given <var>query</var>.
+   *
+   * @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
+   * @throws LexerException if <var>query</var> can't be tokenized
+   * @throws ParserException if the <var>query</var> is not syntactically
+   *      correct
+   */
+  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;
+  }
+
+
+  /**
+   * Execute an iTQL &quot;update&quot; statement that returns no results.
+   * <p>
+   *   This method should be used only for commands that return no results
+   *   such as <code>INSERT</code> and <code>ALIAS</code>.
+   * </p>
+   *
+   * @param itql The statement to execute.
+   *
+   * @throws ItqlInterpreterException if the statement fails or the command
+   *   executed returned results.
+   */
+  public void executeUpdate(String itql) throws ItqlInterpreterException {
+
+    try {
+      executeCommand(itql);
+    } catch (Exception e) {
+      throw new ItqlInterpreterException(e);
+    }
+
+    Exception e = interpreter.getLastException();
+    ItqlInterpreterException exception = (e == null) ? null : new ItqlInterpreterException(e);
+    Answer answer = interpreter.getLastAnswer();
+
+    if (answer != null) {
+
+      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;
+  }
+
+
+  /**
+   * Returns true if a quit command has been entered.
+   *
+   * @return true if a quit command has been entered
+   */
+  public boolean isQuitRequested() {
+    return quit;
+  }
+
+
+  /**
+   * Returns the {@linkplain TqlAutoInterpreter#getLastMessage last message} of
+   * the interpreter.
+   *
+   * @return the results of the last command execution, null if the command did
+   *      not set any message
+   *
+   * @see TqlAutoInterpreter#getLastMessage()
+   */
+  public String getLastMessage() {
+    return interpreter.getLastMessage();
+  }
+
+
+  /**
+   * Returns the {@linkplain TqlAutoInterpreter#getLastException last error} of
+   * the interpreter.
+   *
+   * @return the results of the last command execution, null if the command did
+   *      not set any message
+   *
+   * @see TqlAutoInterpreter#getLastException()
+   */
+  public ItqlInterpreterException getLastError() {
+    return new ItqlInterpreterException(interpreter.getLastException());
+  }
+
+
+  /**
+   * Execute an ITQL query and return an answer.
+   *
+   * @param itql The query to execute.
+   * @return The answer to the query.
+   * @throws ItqlInterpreterException if the query fails.
+   */
+  public Answer executeQuery(String itql) throws ItqlInterpreterException {
+    try {
+      executeCommand(itql);
+    } catch (Exception e) {
+      throw new ItqlInterpreterException(e);
+    }
+
+    Exception exception = interpreter.getLastException();
+    if (exception != null) throw new ItqlInterpreterException(exception);
+
+    return interpreter.getLastAnswer();
+  }
+
+
+  /**
+   * Load the contents of a local file into a database/model.
+   * <p>
+   *   The method assumes the source to be RDF/XML if an .rdf extension can
+   *   not be found.  A .n3 extension assume n3 triples.
+   * </p>
+   * <p>
+   *   Note. <var>destinationURI</var> must be a valid URI, and does not include
+   *   the angle brackets (&lt; and &gt;) used to delimit URLs in iTQL.
+   * </p>
+   *
+   * @param sourceFile  a local file containing the source data
+   * @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 or the file does not exist
+   * on the local file system.
+   */
+  public long load(File sourceFile, URI destinationURI) throws QueryException {
+    long numberOfStatements = 0;
+
+    // check for the local file
+    if (!sourceFile.exists()) {
+      throw new QueryException(sourceFile+" does not exist on the local file system");
+    }
+    try {
+      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;
+   }
+
+
+  /**
+   * Backup all the data on the specified server to a client local file.
+   * The database is not changed by this method.
+   *
+   * @param sourceURI The URI of the server 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.
+   */
+  @SuppressWarnings("deprecation")
+  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 (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.
+   *
+   * @param sourceURI The URI of the server to backup.
+   * @param outputStream The stream to receive the contents
+   * @throws QueryException if the backup cannot be completed.
+   */
+  @SuppressWarnings("deprecation")
+  public void backup(URI sourceURI, OutputStream outputStream) throws QueryException {
+    Backup backup = new Backup(sourceURI, null, true);
+    backup.setOverrideOutputStream(outputStream);
+    try {
+      backup.execute(interpreter.establishConnection(backup.getServerURI()));
+    } catch (ConnectionException e) {
+      throw new QueryException("Unable to establish connection to: " + backup.getServerURI(), e);
+    }
+  }
+  
+  
+  /**
+   * Export the data in the specified graph to a client local file.
+   * The database is not changed by this method.
+   *
+   * @param graphURI The URI of the graph to export.
+   * @param destinationFile an non-existent file on the local file system to
+   * receive the export contents.
+   * @throws QueryException if the export cannot be completed.
+   */
+  public void export(URI graphURI, File destinationFile) throws QueryException {
+    Export export = new Export(graphURI, destinationFile.toURI(), true);
+    try {
+      export.execute(interpreter.establishConnection(export.getServerURI()));
+    } catch (ConnectionException e) {
+      throw new QueryException("Unable to establish connection to: " + export.getServerURI(), e);
+    }
+  }
+  
+  
+  /**
+   * Export the data in the specified graph to an output stream.
+   * The database is not changed by this method.
+   *
+   * @param graphURI The URI of the graph to export.
+   * @param outputStream The stream to receive the contents
+   * @throws QueryException if the export cannot be completed.
+   */
+  public void export(URI graphURI, OutputStream outputStream) throws QueryException {
+    Export export = new Export(graphURI, outputStream);
+    try {
+      export.execute(interpreter.establishConnection(export.getServerURI()));
+    } catch (ConnectionException e) {
+      throw new QueryException("Unable to establish connection to: " + export.getServerURI(), e);
+    }
+  }
+
+
+  /**
+   * Load the contents of an InputStream into a database/model.  The method assumes
+   * the source to be RDF/XML.
+   * <p>
+   *   Note. <var>destinationURI</var> must be a valid URI, and does not include
+   *   the angle brackets (&lt; and &gt;) used to delimit URLs in iTQL.
+   * </p>
+   *
+   * @param inputStream a locally supplied inputstream.
+   * @param destinationURI destination model for the source data
+   * @return number of rows inserted into the destination model
+   */
+  public long load(InputStream inputStream, URI destinationURI) throws QueryException {
+    return load(inputStream, null, destinationURI);
+  }
+
+
+  /**
+   * Load the contents of an InputStream or a URI into a database/model.
+   * <p>
+   *   Note. <var>destinationURI</var> must be a valid URI, and does not include
+   *   the angle brackets (&lt; and &gt;) used to delimit URLs in iTQL.
+   * </p>
+   *
+   * @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 {
+    long numberOfStatements = 0;
+    try {
+      Load loadCmd = new Load(sourceURI, destinationURI, true);
+      loadCmd.setOverrideInputStream(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
+   * content and the content of the backup file when this method returns.
+   *
+   * @param inputStream An input 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 {
+     restore(inputStream, serverURI, null);
+  }
+
+
+  /**
+   * 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.
+   */
+  @SuppressWarnings("deprecation")
+  public void restore(InputStream inputStream, URI serverURI, URI sourceURI) throws QueryException {
+    try {
+      Restore restoreCmd = new Restore(sourceURI, serverURI, true);
+      restoreCmd.setOverrideInputStream(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);
+    }
+  }
+
+
+  /**
+   * @param answer the answer to convert into XML
+   * @param parent the XML element to add the query solutions to
+   * @throws QueryException if the solutions can't be added
+   */
+  private void appendSolution(Answer answer, Element parent)
+    throws QueryException {
+
+    try {
+      Document doc = parent.getOwnerDocument();
+
+      Element VARIABLES = doc.createElementNS(TQL_NS, "variables");
+
+      // Add the variable list
+      Element variables = (Element) parent.appendChild(VARIABLES);
+
+      for (int column = 0; column < answer.getVariables().length; column++) {
+        variables.appendChild(doc.createElement(answer.getVariables()[column].getName()));
+      }
+
+      // Add any solutions
+      answer.beforeFirst();
+
+      while (answer.next()) {
+
+        Element solution = doc.createElementNS(TQL_NS, "solution");
+
+        for (int column = 0; column < answer.getVariables().length; column++) {
+
+          Object object = answer.getObject(column);
+
+          // If the node is null, don't add a tag at all
+          if (object == null) continue;
+
+          // Otherwise, add a tag for the node
+          Element variable =
+              (Element) solution.appendChild(doc.createElementNS(TQL_NS,
+              answer.getVariables()[column].getName()));
+
+          if (object instanceof Answer) {
+
+            Answer tmpAnswer = (Answer) object;
+            try {
+              appendSolution(tmpAnswer, variable);
+            } finally {
+              tmpAnswer.close();
+            }
+
+          } else if (object instanceof LiteralImpl) {
+
+            LiteralImpl literal = (LiteralImpl)object;
+            if (literal.getDatatypeURI() != null) {
+              variable.setAttribute("datatype", literal.getDatatypeURI().toString());
+            }
+            String language = literal.getLanguage();
+            if (language != null && language.length() != 0) {
+              variable.setAttribute("language", language);
+            }
+            variable.appendChild(doc.createTextNode(literal.getLexicalForm()));
+          } else if (object instanceof URIReference) {
+
+            variable.setAttribute("resource", ((URIReference)object).getURI().toString());
+          } else if (object instanceof BlankNode) {
+
+            variable.setAttribute("blank-node", object.toString());
+          } else {
+            throw new AssertionError("Unknown RDFNode type: " + object.getClass());
+          }
+        }
+
+        parent.appendChild(solution);
+      }
+    } catch (TuplesException e) {
+      throw new QueryException("Couldn't build query", e);
+    }
+  }
+
+
+  //
+  // Internal methods
+  //
+
+  /**
+   * Executes the <var>query</var> , returning a &quot;nice&quot; result. <p>
+   *
+   * The result is either a {@link java.lang.String} or a {@link
+   * org.mulgara.query.Answer}. Any exceptions are logged, gobbled and return
+   * as a {@link java.lang.String}. </p>
+   *
+   * @param query the query to execute
+   * @param keepExceptions keep exceptions, don't convert to a message.
+   * @return the result of the query in a &quot;nice&quot; format
+   */
+  private Object executeQueryToNiceResult(String query, boolean keepExceptions) {
+
+    // create the result
+    Object result = null;
+
+    try {
+
+      // get the answer to the 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.getLastException() != null) {
+
+          // error has occurred at the interpreter
+          if (log.isDebugEnabled()) {
+            log.debug("Adding query error to map - " + this.interpreter.getLastException());
+          }
+
+          // end if
+          // set this as the answer
+          if (keepExceptions) {
+            result = this.interpreter.getLastException();
+          } else {
+            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());
+          }
+
+          // end if
+          // set this as the answer
+          result = interpreter.getLastMessage();
+        }
+
+        // end if
+      }
+
+      // end if
+    } catch (Exception e) {
+
+      if (keepExceptions) {
+        result = e;
+      } else {
+
+        // get root cause exception
+        Throwable cause = e.getCause();
+        Throwable lastCause = e;
+
+        while (cause != null) {
+          lastCause = cause;
+          cause = cause.getCause();
+        }
+
+        // end while
+        // format the exception message
+        String exceptionMessage = lastCause.getMessage();
+
+        if (exceptionMessage == null) {
+          exceptionMessage = lastCause.toString();
+        }
+
+        // end if
+        // turn it into a pretty string
+        exceptionMessage = "Query Error: " + exceptionMessage;
+
+        // log the message
+        if (log.isDebugEnabled()) {
+          log.debug(exceptionMessage);
+        }
+
+        // end if
+        // add the exception message to the answers
+        result = exceptionMessage;
+
+        // log full stack trace
+        StringWriter stringWriter = new StringWriter();
+        PrintWriter printWriter = new PrintWriter(stringWriter);
+        e.printStackTrace(printWriter);
+        printWriter.flush();
+        stringWriter.flush();
+
+        log.error("Error while processing query: '" + query + "' " + EOL +
+            stringWriter.getBuffer().toString());
+      }
+    }
+
+    return result;
+  }
+
+
+  /**
+    * 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) {
+    // Do nothing
+  }
+
+
+  /**
+   * Sets the aliases associated with this bean.
+   *
+   * @param aliasMap the alias map associated with this bean
+   */
+  @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.clearLastException();
+  }
+
+ /**
+  * Ensures all resources are closed at GC.
+  * Especially important if this object is in a servlet
+  * 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);
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,937 +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;
-
-import org.mulgara.query.Answer;
-import org.mulgara.query.QueryException;
-import org.mulgara.server.SessionFactory;
-import org.mulgara.server.driver.SessionFactoryFinder;
-import org.mulgara.util.TempDir;
-
-// third party packages
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-// Java 2 standard packages
-import java.net.URL;
-import java.util.Vector;
-import java.net.*;
-import java.rmi.server.UnicastRemoteObject;
-import java.io.File;
-import java.io.FileOutputStream;
-
-// third party packages
-import javax.xml.parsers.FactoryConfigurationError;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.xml.DOMConfigurator; // Soap packages
-
-// Soap packages
-import org.apache.soap.Constants;
-import org.apache.soap.Fault;
-import org.apache.soap.rpc.*;
-
-// emory util package
-import edu.emory.mathcs.util.remote.io.*;
-import edu.emory.mathcs.util.remote.io.server.impl.*;
-
-/**
- * Unit test for {@link ItqlInterpreterBeanUnitTest}.
- *
- * @created 2001-11-19
- *
- * @author Tate Jones
- *
- * @version $Revision: 1.9 $
- *
- * @modified $Date: 2005/01/05 05:13:59 $ by $Author: newmana $
- *
- * @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 ItqlInterpreterBeanUnitTest extends TestCase {
-
-  //
-  // Members
-  //
-
-  /** The category to send logging info to */
-  private static final Logger log = Logger.getLogger(ItqlInterpreterBeanUnitTest.class);
-
-  /** Description of the Field */
-  private ItqlInterpreterBean bean = null;
-
-  /** host name of server */
-  private static String hostName = System.getProperty("host.name");
-
-  /** an example model */
-  private static String testModel = "rmi://" + hostName + "/server1#itqlmodel";
-
-  /** Data directory for test files */
-  private static String dataDirectory = System.getProperty("cvs.root") + "/data";
-
-  static {
-    if ( System.getProperty("os.name").indexOf("Windows") >= 0 ) {
-      dataDirectory = "/"+dataDirectory.replace('\\','/');
-    }
-  }
-
-  /** a temp directory location */
-  private static File tmpDirectory = TempDir.getTempDir();
-
-  //
-  // Public API
-  //
-
-  /**
-   * Constructs a new ItqlInterpreter unit test.
-   *
-   * @param name the name of the test
-   */
-  public ItqlInterpreterBeanUnitTest(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");
-    }
-
-  }
-
-  /**
-   * 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 ItqlInterpreterBeanUnitTest("testQuery1"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testQuery2"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testQuery3"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testAnswerIteration"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testCreateModel"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi1"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi2"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi3"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi4"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi5"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi6"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi7"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi8"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi9"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testBackupApi1"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testBackupApi2"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testExportApi1"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testExportApi2"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testRestoreApi1"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testRoundTrip1"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testMultipleBeanTest"));
-    suite.addTest(new ItqlInterpreterBeanUnitTest("testExplicitSession"));
-
-    return suite;
-  }
-
-  /**
-   * The main program for the ItqlInterpreterBeanUnitTest class
-   *
-   * @param args The command line arguments
-   * @throws Exception General catch-all for exceptions thrown during the entire test suite
-   */
-  public static void main(String[] args) throws Exception {
-
-    junit.textui.TestRunner.run(suite());
-  }
-  
-  /**
-   * Convert Windows line endings...
-   */
-  private static String convertLineEndings(String str) {
-    String converted = str;
-    if (System.getProperty("os.name").toLowerCase().indexOf("win") > -1) {
-      converted = converted.replaceAll("\r\n", "\n");
-    }
-    return converted;
-  }
-
-  /**
-   * Test the interpreter via a direct call and a SOAP call
-   *
-   * @throws Exception if the test fails
-   */
-  public void testQuery1() throws Exception {
-
-    String queryString =
-        "select $s $p $o from <rmi://" + hostName +
-        "/server1#> where $s $p $o ;";
-
-    String directAnswer = bean.executeQueryToString(queryString);
-    directAnswer = convertLineEndings(directAnswer);
-    String soapAnswer = this.executeSoapCall(queryString);
-
-    assertEquals(
-        "A basic SELECT SOAP iTQL result is not the same as a direct call",
-        soapAnswer, directAnswer);
-  }
-
-  /**
-   * A unit test for JUnit
-   *
-   * @throws Exception General catch-all for exceptions thrown during the test
-   */
-  public void testQuery2() throws Exception {
-
-    String queryString = "create <rmi://" + hostName + "/server1#model> ;";
-    String directAnswer = bean.executeQueryToString(queryString);
-    directAnswer = convertLineEndings(directAnswer);
-    String soapAnswer = this.executeSoapCall(queryString);
-
-    assertEquals("A CREATE SOAP iTQL result is not the same as a direct call",
-        soapAnswer, directAnswer);
-  }
-
-  /**
-   * A unit test for JUnit
-   *
-   * @throws Exception General catch-all for exceptions thrown during the test
-   */
-  public void testQuery3() throws Exception {
-
-    String queryString =
-        "insert <http://google.blogspace.com/archives/000999836> <http://purl.org/rss/1.0/description> 'Google needs to stop sending it\\'s cookie and promise to only store aggregate data, with no connection between users and search terms. ; This issue was publically raised almost a year ago that Google still hasnt dealt with its inexcusable....' into <rmi://" +
-        hostName + "/server1#model>;";
-
-    String result =
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<answer xmlns=\"http://mulgara.org/tql#\"><query><message>Successfully inserted statements into rmi://" +
-        hostName + "/server1#model</message></query></answer>";
-
-    String directAnswer = bean.executeQueryToString(queryString);
-    directAnswer = convertLineEndings(directAnswer);
-    String soapAnswer = this.executeSoapCall(queryString);
-
-    if (log.isDebugEnabled()) {
-      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) + "'");
-    }
-
-    assertEquals("A insert SOAP iTQL result is not the same as a direct call",
-        soapAnswer, directAnswer);
-    assertEquals("Incorrect iTQL result found", soapAnswer, result);
-  }
-
-  /**
-   * A unit test for JUnit. Tests that an Answer can be obtained and
-   * iterated over and reset multiple times.
-   *
-   * @throws Exception General catch-all for exceptions thrown during the test
-   */
-  public void testAnswerIteration() throws Exception {
-
-    //create model
-    String model = "rmi://" + hostName + "/server1#answerModel";
-    String query = "create <" + model + "> ;";
-    bean.executeQueryToString(query);
-
-    //load data
-    String dataFile = "file:" + dataDirectory + "/numbers.rdf.gz";
-    query = "load <" + dataFile + "> into <" + model + "> ;";
-    //number of statements must be more than 1 page size (1000 statements)
-    System.setProperty("mulgara.rmi.prefetchsize", "10");
-    bean.executeQueryToString(query);
-    bean.executeQueryToString(query);
-
-    //get Answer (everything)
-    query = "select $s $p $o from <" + model + "> where $s $p $o;";
-    Answer result = bean.executeQuery(query);
-    result.close();
-
-    //iterate and re-iterate - ensuring rowCount is preserved
-    try {
-      result = bean.executeQuery(query);
-      //determine the number of statements in the Answer
-      long rowCount = result.getRowCount();
-      long statementCount = 0;
-
-      //number of times to iterate
-      int NUM_ITERATIONS = 10;
-      for (int i = 0; i < NUM_ITERATIONS; i++) {
-        //count to the end of Answer
-        while (result.next()) {
-          statementCount++;
-        }
-        //ensure all statements were preserved
-        assertEquals("Number of Statements in Answer has changed after " +
-            "iteration: " + i + ". Answer: " + result.getClass().getName(),
-            rowCount, statementCount);
-
-        //reset
-        result.beforeFirst();
-        statementCount = 0;
-      }
-    } finally {
-      try {
-        result.close();
-      } finally {
-        //drop the model
-        bean.executeQueryToString("drop <" + model + "> ;");
-      }
-    }
-  }
-
-  /**
-   * Performs a query over the SOAP interface
-   *
-   * @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");
-
-    // Build the call.
-    Call call = new Call();
-    call.setTargetObjectURI("urn:Query");
-    call.setMethodName("executeQueryToString");
-
-    //call.setEncodingStyleURI(Constants.NS_URI_LITERAL_XML);
-    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
-
-    Vector<Parameter> params = new Vector<Parameter>();
-    params.addElement(new Parameter("queryString", String.class, query,
-        Constants.NS_URI_SOAP_ENC));
-    call.setParams(params);
-
-    // make the call: note that the action URI is empty because the
-    // XML-SOAP rpc router does not need this. This may change in the
-    // future.
-    Response resp = call.invoke( /* router URL */
-        url, /* actionURI */
-        "");
-
-    // Check the response.
-    if (resp.generatedFault()) {
-
-      Fault fault = resp.getFault();
-      fail("Soap call has failed : Fault Code   = " + fault.getFaultCode() +
-          " Fault String = " + fault.getFaultString());
-
-      return fault.getFaultCode() + " - " + fault.getFaultString();
-    } else {
-
-      Parameter result = resp.getReturnValue();
-
-      return result.getValue().toString();
-    }
-  }
-
-  /**
-   * 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 testCreateModel() throws Exception {
-
-    // log that we're executing the test
-    log.debug("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
-    bean.executeQuery(statement);
-    results = bean.getLastMessage();
-
-    // log the results
-    log.debug("Received results : " + results);
-
-    // log that we've completed the test
-    log.debug("Completed create test 3");
-  }
-
-  /**
-   * 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.debug("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 = bean.load(null, sourceURI, modelURI);
-
-    assertEquals("Incorrect number of statements inserted", 154, statements);
-  }
-
-  // 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.debug("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 = bean.load(inputStream,
-        sourceURI, modelURI);
-
-    assertEquals("Incorrect number of statements inserted", 154, statements);
-
-    inputStream.close();
-
-  }
-
-  // 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.debug("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 = bean.load(sourceURI.toURL().openStream(),
-        dummyURI, modelURI);
-
-    assertEquals("Incorrect number of statements inserted", 154, statements);
-
-  }
-
-  /**
-   * 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.debug("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 = bean.load(sourceURI.toURL().openStream(),
-        modelURI);
-
-    assertEquals("Incorrect number of statements inserted", 154, statements);
-
-  }
-
-  /**
-   * Test the interpreter using a load API locally
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi5() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting load API test 5");
-
-    File source = new File(dataDirectory + "/ical.rdf");
-    URI modelURI = new URI(testModel);
-
-    // execute the load locally
-    long statements = bean.load(source, modelURI);
-
-    assertEquals("Incorrect number of statements inserted", 1482, statements);
-
-  }
-
-  /**
-   * Test the interpreter using a load API locally
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi6() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting load API test 6");
-
-    File source = new File(dataDirectory + "/camera.owl");
-    URI modelURI = new URI(testModel);
-
-    // execute the load locally
-    long statements = bean.load(source, modelURI);
-
-    assertEquals("Incorrect number of statements inserted", 103, statements);
-
-  }
-
-  /**
-   * Test the interpreter using a load API locally
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi7() throws Exception {
-
-    boolean badFile = false;
-
-    // log that we're executing the test
-    log.debug("Starting load API test 7");
-
-    File source = new File(dataDirectory + "/camera.owl.bad");
-    URI modelURI = new URI(testModel);
-
-    // execute the load locally
-    try {
-      bean.load(source, modelURI);
-    } catch (QueryException ex) {
-      badFile = true;
-    }
-
-    assertTrue("Excepting a bad file", badFile);
-
-  }
-
-  /**
-   * Test the interpreter using a load API locally
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi8() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting load API test 8");
-
-    File source = new File(dataDirectory + "/camera.n3");
-    URI modelURI = new URI(testModel);
-
-    // execute the load locally
-    long statements = bean.load(source, modelURI);
-
-    assertEquals("Incorrect number of statements inserted", 99, statements);
-
-  }
-
-  /**
-   * Test the interpreter using a load API locally with a GZip file.
-   *
-   * @throws Exception if the test fails
-   */
-  public void testLoadApi9() throws Exception {
-
-    try {
-
-      // log that we're executing the test
-      log.debug("Starting load API test 9");
-
-      File source = new File(dataDirectory + "/numbers.rdf.gz");
-      URI modelURI = new URI(testModel);
-
-      // execute the load locally
-      long statements = bean.load(source, modelURI);
-
-      assertEquals("Incorrect number of statements inserted", 512, statements);
-    } catch (Exception exception) {
-
-      exception.printStackTrace();
-      throw exception;
-    }
-  }
-
-  /**
-   * Test the interpreter using a backup API locally.
-   * Expects the server to exist
-   *
-   * @throws Exception if the test fails
-   */
-  public void testBackupApi1() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting backup API test 2");
-
-    File file = new File(tmpDirectory, "server.gz");
-    file.delete();
-
-    URI serverURI = new URI("rmi://localhost/server1");
-
-    bean.backup(serverURI, file);
-
-    assertTrue("Excepting a backup file", file.exists());
-
-  }
-
-  /**
-   * Test the interpreter using a backup API locally.
-   * Expects the server to exist
-   *
-   * @throws Exception if the test fails
-   */
-  public void testBackupApi2() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting backup API test 4");
-
-    File file = new File(tmpDirectory, "server2.gz");
-    file.delete();
-
-    URI serverURI = new URI("rmi://localhost/server1");
-
-    bean.backup(serverURI, new FileOutputStream(file));
-
-    assertTrue("Excepting a backup file", file.exists());
-
-  }
-
-  /**
-   * Test the interpreter using an export API locally.
-   * Expects the test model to exist
-   *
-   * @throws Exception if the test fails
-   */
-  public void testExportApi1() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting backup API test 1");
-
-    File file = new File(tmpDirectory, "camera.rdf");
-    file.delete();
-
-    URI modelURI = new URI(testModel);
-
-    bean.export(modelURI, file);
-
-    assertTrue("Excepting a backup file", file.exists());
-
-  }
-
-  /**
-   * Test the interpreter using an export API locally.
-   * Expects the test model to exist
-   *
-   * @throws Exception if the test fails
-   */
-  public void testExportApi2() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting backup API test 3");
-
-    File file = new File(tmpDirectory, "camera2.rdf");
-    file.delete();
-
-    URI modelURI = new URI(testModel);
-
-    bean.export(modelURI, new FileOutputStream(file));
-
-    assertTrue("Excepting a backup file", file.exists());
-
-  }
-
-  /**
-   * Test the interpreter using a restore API locally.
-   * Expects the server to exist
-   *
-   * @throws Exception if the test fails
-   */
-  @SuppressWarnings("deprecation")
-  public void testRestoreApi1() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting restore API test 1");
-
-    File file = new File(tmpDirectory, "server2.gz");
-
-    URI serverURI = new URI("rmi://localhost/server1");
-
-    bean.restore(file.toURL().openStream(), serverURI);
-
-  }
-
-  /**
-   * Test a round trip of backup and restore
-   *
-   * This will test relative and absolute URIs to the server host name.
-   *
-   * @throws Exception if the test fails
-   */
-  @SuppressWarnings("deprecation")
-  public void testRoundTrip1() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting round trip test 1");
-
-    URI serverURI = new URI("rmi://" + hostName + "/server1");
-
-    // test the output
-    String select = "select $o from <" + testModel + "> " +
-        "where <rmi://" + hostName +
-        "/server1> <http://purl.org/dc/elements/1.1/creator> $o or " +
-        " <rmi://" + hostName +
-        "/foobar> <http://purl.org/dc/elements/1.1/creator> $o or " +
-        " <rmi://" + hostName +
-        "/server1/foobar> <http://purl.org/dc/elements/1.1/creator> $o ;";
-
-    // insert statements with a subject the same as the
-    // server name
-    String insert = "insert " +
-        "<rmi://" + hostName +
-        "/server1> <http://purl.org/dc/elements/1.1/creator> 'foo' " +
-        "<rmi://" + hostName +
-        "/foobar> <http://purl.org/dc/elements/1.1/creator> 'foobar' " +
-        "<rmi://" + hostName +
-        "/server1/foobar> <http://purl.org/dc/elements/1.1/creator> 'server1/foobar' " +
-        " into <" + testModel + ">;";
-
-    // insert the statement
-    bean.executeQuery(insert);
-
-    // select the statement
-    Answer answer = bean.executeQuery(select);
-    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));
-    assertTrue("Excepting a backup file", file.exists());
-
-    // restore the server
-    bean.restore(file.toURL().openStream(), serverURI);
-
-    // select the statement
-    answer = bean.executeQuery(select);
-    assertTrue("Excepting a answer after restore", answer != null);
-    assertTrue("Excepting a single result and found :" +
-        answer.getRowCount(), (answer.getRowCount() == 3));
-
-  }
-
-  /**
-   * Test the multiple creations of the interpreterbean
-   * Ensure the number of open files are not exceeded on OS.
-   *
-   */
-  public void testMultipleBeanTest() {
-
-    /*
-         // keep a track of the number of session directories
-         String sessionDir = testDir + File.separator +
-                             "server1" + File.separator +
-                             "sessions" + File.separator;
-
-         System.out.println("Session dir is "+ sessionDir );
-
-         // log that we're executing the test
-         log.debug("Starting multiple bean test");
-
-
-         // get the initial number of directories
-         int initNumberOfSessionDirs = (new File(sessionDir)).list().length;
-     log.debug("Initial number of session directories are "+initNumberOfSessionDirs);
-     */
-
-    String query = "select $s $p $o from <rmi://" + hostName +
-        "/server1#> where $s $p $o;";
-
-    // create a 100 beans
-    // TODO: change back to 1000
-    for (int count = 1; count < 100; count++) {
-      ItqlInterpreterBean bean = null;
-      Answer answer = null;
-      try {
-        // create a new bean.
-        bean = new ItqlInterpreterBean();
-
-        log.warn("Starting bean number " + count);
-
-        // execute a basic query
-        answer = bean.executeQuery(query);
-        assertTrue("Failed to query system model", answer.getRowCount() > 0);
-        answer.close();
-
-      } 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 {
-        bean.close();
-      }
-    }
-
-    /*
-         // get the end number of directories
-         int endNumberOfSessionDirs = (new File(sessionDir)).list().length;
-     log.debug("The end number of session directories are "+endNumberOfSessionDirs);
-
-         // the init and end number of directories should be the same
-     assertTrue("Expecting "+initNumberOfSessionDirs+" session to exist, but "+
-               "found "+endNumberOfSessionDirs+" session directories",
-               endNumberOfSessionDirs == initNumberOfSessionDirs);
-     */
-  }
-
-  /**
-   * Test giving ItqlInterpreterBean an explicit session.
-   *
-   * @throws Exception if the test fails
-   */
-  @SuppressWarnings("deprecation")
-  public void testExplicitSession() throws Exception {
-
-    // log that we're executing the test
-    log.debug("Starting explicit session test");
-
-    URI serverURI = new URI("rmi://" + hostName + "/server1");
-    SessionFactory sessionFactory =
-                      SessionFactoryFinder.newSessionFactory(serverURI, true);
-
-    bean.close();
-    bean = new ItqlInterpreterBean(sessionFactory.newSession(),
-                                   sessionFactory.getSecurityDomain());
-
-    // auto-commit = true
-    bean.executeQuery(
-        "insert <es:foo1> <es:bar1> 'foo' into <" + testModel + ">;");
-
-    Answer answer = bean.executeQuery(
-        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
-    assertEquals("Expecting a single result", 1, answer.getRowCount());
-
-    bean.executeQuery(
-        "delete <es:foo1> <es:bar1> 'foo' from <" + testModel + ">;");
-
-    answer = bean.executeQuery(
-        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
-    assertEquals("Expecting no results", 0, answer.getRowCount());
-
-    // explicit tx with commit
-    bean.beginTransaction("explicit-session-test-commit");
-
-    bean.executeQuery(
-        "insert <es:foo1> <es:bar1> 'foo' into <" + testModel + ">;");
-
-    answer = bean.executeQuery(
-        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
-    assertEquals("Expecting a single result", 1, answer.getRowCount());
-
-    bean.executeQuery(
-        "delete <es:foo1> <es:bar1> 'foo' from <" + testModel + ">;");
-
-    bean.commit("explicit-session-test-commit");
-
-    answer = bean.executeQuery(
-        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
-    assertEquals("Expecting no results", 0, answer.getRowCount());
-
-    // explicit tx with rollback
-    bean.beginTransaction("explicit-session-test-rollback");
-
-    bean.executeQuery(
-        "insert <es:foo1> <es:bar1> 'foo' into <" + testModel + ">;");
-
-    answer = bean.executeQuery(
-        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
-    assertEquals("Expecting a single result", 1, answer.getRowCount());
-
-    bean.rollback("explicit-session-test-rollback");
-
-    answer = bean.executeQuery(
-        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
-    assertEquals("Expecting no results", 0, answer.getRowCount());
-  }
-
-
-  // ItqlInt
-
-  /**
-   * Initialise members.
-   *
-   * @throws Exception if something goes wrong
-   */
-  protected void setUp() throws Exception {
-
-    bean = new ItqlInterpreterBean();
-  }
-
-  protected void tearDown() throws Exception {
-    if (bean != null) {
-      try {
-        bean.close();
-      } finally {
-        bean = null;
-      }
-    }
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterBeanUnitTest.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,937 @@
+/*
+ * 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;
+
+import org.mulgara.query.Answer;
+import org.mulgara.query.QueryException;
+import org.mulgara.server.SessionFactory;
+import org.mulgara.server.driver.SessionFactoryFinder;
+import org.mulgara.util.TempDir;
+
+// third party packages
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+// Java 2 standard packages
+import java.net.URL;
+import java.util.Vector;
+import java.net.*;
+import java.rmi.server.UnicastRemoteObject;
+import java.io.File;
+import java.io.FileOutputStream;
+
+// third party packages
+import javax.xml.parsers.FactoryConfigurationError;
+
+import org.apache.log4j.Logger;
+import org.apache.log4j.xml.DOMConfigurator; // Soap packages
+
+// Soap packages
+import org.apache.soap.Constants;
+import org.apache.soap.Fault;
+import org.apache.soap.rpc.*;
+
+// emory util package
+import edu.emory.mathcs.util.remote.io.*;
+import edu.emory.mathcs.util.remote.io.server.impl.*;
+
+/**
+ * Unit test for {@link ItqlInterpreterBeanUnitTest}.
+ *
+ * @created 2001-11-19
+ *
+ * @author Tate Jones
+ *
+ * @version $Revision: 1.9 $
+ *
+ * @modified $Date: 2005/01/05 05:13:59 $ by $Author: newmana $
+ *
+ * @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 ItqlInterpreterBeanUnitTest extends TestCase {
+
+  //
+  // Members
+  //
+
+  /** The category to send logging info to */
+  private static final Logger log = Logger.getLogger(ItqlInterpreterBeanUnitTest.class);
+
+  /** Description of the Field */
+  private ItqlInterpreterBean bean = null;
+
+  /** host name of server */
+  private static String hostName = System.getProperty("host.name");
+
+  /** an example model */
+  private static String testModel = "rmi://" + hostName + "/server1#itqlmodel";
+
+  /** Data directory for test files */
+  private static String dataDirectory = System.getProperty("cvs.root") + "/data";
+
+  static {
+    if ( System.getProperty("os.name").indexOf("Windows") >= 0 ) {
+      dataDirectory = "/"+dataDirectory.replace('\\','/');
+    }
+  }
+
+  /** a temp directory location */
+  private static File tmpDirectory = TempDir.getTempDir();
+
+  //
+  // Public API
+  //
+
+  /**
+   * Constructs a new ItqlInterpreter unit test.
+   *
+   * @param name the name of the test
+   */
+  public ItqlInterpreterBeanUnitTest(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");
+    }
+
+  }
+
+  /**
+   * 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 ItqlInterpreterBeanUnitTest("testQuery1"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testQuery2"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testQuery3"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testAnswerIteration"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testCreateModel"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi1"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi2"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi3"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi4"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi5"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi6"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi7"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi8"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testLoadApi9"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testBackupApi1"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testBackupApi2"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testExportApi1"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testExportApi2"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testRestoreApi1"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testRoundTrip1"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testMultipleBeanTest"));
+    suite.addTest(new ItqlInterpreterBeanUnitTest("testExplicitSession"));
+
+    return suite;
+  }
+
+  /**
+   * The main program for the ItqlInterpreterBeanUnitTest class
+   *
+   * @param args The command line arguments
+   * @throws Exception General catch-all for exceptions thrown during the entire test suite
+   */
+  public static void main(String[] args) throws Exception {
+
+    junit.textui.TestRunner.run(suite());
+  }
+  
+  /**
+   * Convert Windows line endings...
+   */
+  private static String convertLineEndings(String str) {
+    String converted = str;
+    if (System.getProperty("os.name").toLowerCase().indexOf("win") > -1) {
+      converted = converted.replaceAll("\r\n", "\n");
+    }
+    return converted;
+  }
+
+  /**
+   * Test the interpreter via a direct call and a SOAP call
+   *
+   * @throws Exception if the test fails
+   */
+  public void testQuery1() throws Exception {
+
+    String queryString =
+        "select $s $p $o from <rmi://" + hostName +
+        "/server1#> where $s $p $o ;";
+
+    String directAnswer = bean.executeQueryToString(queryString);
+    directAnswer = convertLineEndings(directAnswer);
+    String soapAnswer = this.executeSoapCall(queryString);
+
+    assertEquals(
+        "A basic SELECT SOAP iTQL result is not the same as a direct call",
+        soapAnswer, directAnswer);
+  }
+
+  /**
+   * A unit test for JUnit
+   *
+   * @throws Exception General catch-all for exceptions thrown during the test
+   */
+  public void testQuery2() throws Exception {
+
+    String queryString = "create <rmi://" + hostName + "/server1#model> ;";
+    String directAnswer = bean.executeQueryToString(queryString);
+    directAnswer = convertLineEndings(directAnswer);
+    String soapAnswer = this.executeSoapCall(queryString);
+
+    assertEquals("A CREATE SOAP iTQL result is not the same as a direct call",
+        soapAnswer, directAnswer);
+  }
+
+  /**
+   * A unit test for JUnit
+   *
+   * @throws Exception General catch-all for exceptions thrown during the test
+   */
+  public void testQuery3() throws Exception {
+
+    String queryString =
+        "insert <http://google.blogspace.com/archives/000999836> <http://purl.org/rss/1.0/description> 'Google needs to stop sending it\\'s cookie and promise to only store aggregate data, with no connection between users and search terms. ; This issue was publically raised almost a year ago that Google still hasnt dealt with its inexcusable....' into <rmi://" +
+        hostName + "/server1#model>;";
+
+    String result =
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<answer xmlns=\"http://mulgara.org/tql#\"><query><message>Successfully inserted statements into rmi://" +
+        hostName + "/server1#model</message></query></answer>";
+
+    String directAnswer = bean.executeQueryToString(queryString);
+    directAnswer = convertLineEndings(directAnswer);
+    String soapAnswer = this.executeSoapCall(queryString);
+
+    if (log.isDebugEnabled()) {
+      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) + "'");
+    }
+
+    assertEquals("A insert SOAP iTQL result is not the same as a direct call",
+        soapAnswer, directAnswer);
+    assertEquals("Incorrect iTQL result found", soapAnswer, result);
+  }
+
+  /**
+   * A unit test for JUnit. Tests that an Answer can be obtained and
+   * iterated over and reset multiple times.
+   *
+   * @throws Exception General catch-all for exceptions thrown during the test
+   */
+  public void testAnswerIteration() throws Exception {
+
+    //create model
+    String model = "rmi://" + hostName + "/server1#answerModel";
+    String query = "create <" + model + "> ;";
+    bean.executeQueryToString(query);
+
+    //load data
+    String dataFile = "file:" + dataDirectory + "/numbers.rdf.gz";
+    query = "load <" + dataFile + "> into <" + model + "> ;";
+    //number of statements must be more than 1 page size (1000 statements)
+    System.setProperty("mulgara.rmi.prefetchsize", "10");
+    bean.executeQueryToString(query);
+    bean.executeQueryToString(query);
+
+    //get Answer (everything)
+    query = "select $s $p $o from <" + model + "> where $s $p $o;";
+    Answer result = bean.executeQuery(query);
+    result.close();
+
+    //iterate and re-iterate - ensuring rowCount is preserved
+    try {
+      result = bean.executeQuery(query);
+      //determine the number of statements in the Answer
+      long rowCount = result.getRowCount();
+      long statementCount = 0;
+
+      //number of times to iterate
+      int NUM_ITERATIONS = 10;
+      for (int i = 0; i < NUM_ITERATIONS; i++) {
+        //count to the end of Answer
+        while (result.next()) {
+          statementCount++;
+        }
+        //ensure all statements were preserved
+        assertEquals("Number of Statements in Answer has changed after " +
+            "iteration: " + i + ". Answer: " + result.getClass().getName(),
+            rowCount, statementCount);
+
+        //reset
+        result.beforeFirst();
+        statementCount = 0;
+      }
+    } finally {
+      try {
+        result.close();
+      } finally {
+        //drop the model
+        bean.executeQueryToString("drop <" + model + "> ;");
+      }
+    }
+  }
+
+  /**
+   * Performs a query over the SOAP interface
+   *
+   * @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");
+
+    // Build the call.
+    Call call = new Call();
+    call.setTargetObjectURI("urn:Query");
+    call.setMethodName("executeQueryToString");
+
+    //call.setEncodingStyleURI(Constants.NS_URI_LITERAL_XML);
+    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
+
+    Vector<Parameter> params = new Vector<Parameter>();
+    params.addElement(new Parameter("queryString", String.class, query,
+        Constants.NS_URI_SOAP_ENC));
+    call.setParams(params);
+
+    // make the call: note that the action URI is empty because the
+    // XML-SOAP rpc router does not need this. This may change in the
+    // future.
+    Response resp = call.invoke( /* router URL */
+        url, /* actionURI */
+        "");
+
+    // Check the response.
+    if (resp.generatedFault()) {
+
+      Fault fault = resp.getFault();
+      fail("Soap call has failed : Fault Code   = " + fault.getFaultCode() +
+          " Fault String = " + fault.getFaultString());
+
+      return fault.getFaultCode() + " - " + fault.getFaultString();
+    } else {
+
+      Parameter result = resp.getReturnValue();
+
+      return result.getValue().toString();
+    }
+  }
+
+  /**
+   * 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 testCreateModel() throws Exception {
+
+    // log that we're executing the test
+    log.debug("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
+    bean.executeQuery(statement);
+    results = bean.getLastMessage();
+
+    // log the results
+    log.debug("Received results : " + results);
+
+    // log that we've completed the test
+    log.debug("Completed create test 3");
+  }
+
+  /**
+   * 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.debug("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 = bean.load(null, sourceURI, modelURI);
+
+    assertEquals("Incorrect number of statements inserted", 154, statements);
+  }
+
+  // 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.debug("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 = bean.load(inputStream,
+        sourceURI, modelURI);
+
+    assertEquals("Incorrect number of statements inserted", 154, statements);
+
+    inputStream.close();
+
+  }
+
+  // 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.debug("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 = bean.load(sourceURI.toURL().openStream(),
+        dummyURI, modelURI);
+
+    assertEquals("Incorrect number of statements inserted", 154, statements);
+
+  }
+
+  /**
+   * 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.debug("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 = bean.load(sourceURI.toURL().openStream(),
+        modelURI);
+
+    assertEquals("Incorrect number of statements inserted", 154, statements);
+
+  }
+
+  /**
+   * Test the interpreter using a load API locally
+   *
+   * @throws Exception if the test fails
+   */
+  public void testLoadApi5() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting load API test 5");
+
+    File source = new File(dataDirectory + "/ical.rdf");
+    URI modelURI = new URI(testModel);
+
+    // execute the load locally
+    long statements = bean.load(source, modelURI);
+
+    assertEquals("Incorrect number of statements inserted", 1482, statements);
+
+  }
+
+  /**
+   * Test the interpreter using a load API locally
+   *
+   * @throws Exception if the test fails
+   */
+  public void testLoadApi6() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting load API test 6");
+
+    File source = new File(dataDirectory + "/camera.owl");
+    URI modelURI = new URI(testModel);
+
+    // execute the load locally
+    long statements = bean.load(source, modelURI);
+
+    assertEquals("Incorrect number of statements inserted", 103, statements);
+
+  }
+
+  /**
+   * Test the interpreter using a load API locally
+   *
+   * @throws Exception if the test fails
+   */
+  public void testLoadApi7() throws Exception {
+
+    boolean badFile = false;
+
+    // log that we're executing the test
+    log.debug("Starting load API test 7");
+
+    File source = new File(dataDirectory + "/camera.owl.bad");
+    URI modelURI = new URI(testModel);
+
+    // execute the load locally
+    try {
+      bean.load(source, modelURI);
+    } catch (QueryException ex) {
+      badFile = true;
+    }
+
+    assertTrue("Excepting a bad file", badFile);
+
+  }
+
+  /**
+   * Test the interpreter using a load API locally
+   *
+   * @throws Exception if the test fails
+   */
+  public void testLoadApi8() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting load API test 8");
+
+    File source = new File(dataDirectory + "/camera.n3");
+    URI modelURI = new URI(testModel);
+
+    // execute the load locally
+    long statements = bean.load(source, modelURI);
+
+    assertEquals("Incorrect number of statements inserted", 99, statements);
+
+  }
+
+  /**
+   * Test the interpreter using a load API locally with a GZip file.
+   *
+   * @throws Exception if the test fails
+   */
+  public void testLoadApi9() throws Exception {
+
+    try {
+
+      // log that we're executing the test
+      log.debug("Starting load API test 9");
+
+      File source = new File(dataDirectory + "/numbers.rdf.gz");
+      URI modelURI = new URI(testModel);
+
+      // execute the load locally
+      long statements = bean.load(source, modelURI);
+
+      assertEquals("Incorrect number of statements inserted", 512, statements);
+    } catch (Exception exception) {
+
+      exception.printStackTrace();
+      throw exception;
+    }
+  }
+
+  /**
+   * Test the interpreter using a backup API locally.
+   * Expects the server to exist
+   *
+   * @throws Exception if the test fails
+   */
+  public void testBackupApi1() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting backup API test 2");
+
+    File file = new File(tmpDirectory, "server.gz");
+    file.delete();
+
+    URI serverURI = new URI("rmi://localhost/server1");
+
+    bean.backup(serverURI, file);
+
+    assertTrue("Excepting a backup file", file.exists());
+
+  }
+
+  /**
+   * Test the interpreter using a backup API locally.
+   * Expects the server to exist
+   *
+   * @throws Exception if the test fails
+   */
+  public void testBackupApi2() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting backup API test 4");
+
+    File file = new File(tmpDirectory, "server2.gz");
+    file.delete();
+
+    URI serverURI = new URI("rmi://localhost/server1");
+
+    bean.backup(serverURI, new FileOutputStream(file));
+
+    assertTrue("Excepting a backup file", file.exists());
+
+  }
+
+  /**
+   * Test the interpreter using an export API locally.
+   * Expects the test model to exist
+   *
+   * @throws Exception if the test fails
+   */
+  public void testExportApi1() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting backup API test 1");
+
+    File file = new File(tmpDirectory, "camera.rdf");
+    file.delete();
+
+    URI modelURI = new URI(testModel);
+
+    bean.export(modelURI, file);
+
+    assertTrue("Excepting a backup file", file.exists());
+
+  }
+
+  /**
+   * Test the interpreter using an export API locally.
+   * Expects the test model to exist
+   *
+   * @throws Exception if the test fails
+   */
+  public void testExportApi2() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting backup API test 3");
+
+    File file = new File(tmpDirectory, "camera2.rdf");
+    file.delete();
+
+    URI modelURI = new URI(testModel);
+
+    bean.export(modelURI, new FileOutputStream(file));
+
+    assertTrue("Excepting a backup file", file.exists());
+
+  }
+
+  /**
+   * Test the interpreter using a restore API locally.
+   * Expects the server to exist
+   *
+   * @throws Exception if the test fails
+   */
+  @SuppressWarnings("deprecation")
+  public void testRestoreApi1() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting restore API test 1");
+
+    File file = new File(tmpDirectory, "server2.gz");
+
+    URI serverURI = new URI("rmi://localhost/server1");
+
+    bean.restore(file.toURL().openStream(), serverURI);
+
+  }
+
+  /**
+   * Test a round trip of backup and restore
+   *
+   * This will test relative and absolute URIs to the server host name.
+   *
+   * @throws Exception if the test fails
+   */
+  @SuppressWarnings("deprecation")
+  public void testRoundTrip1() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting round trip test 1");
+
+    URI serverURI = new URI("rmi://" + hostName + "/server1");
+
+    // test the output
+    String select = "select $o from <" + testModel + "> " +
+        "where <rmi://" + hostName +
+        "/server1> <http://purl.org/dc/elements/1.1/creator> $o or " +
+        " <rmi://" + hostName +
+        "/foobar> <http://purl.org/dc/elements/1.1/creator> $o or " +
+        " <rmi://" + hostName +
+        "/server1/foobar> <http://purl.org/dc/elements/1.1/creator> $o ;";
+
+    // insert statements with a subject the same as the
+    // server name
+    String insert = "insert " +
+        "<rmi://" + hostName +
+        "/server1> <http://purl.org/dc/elements/1.1/creator> 'foo' " +
+        "<rmi://" + hostName +
+        "/foobar> <http://purl.org/dc/elements/1.1/creator> 'foobar' " +
+        "<rmi://" + hostName +
+        "/server1/foobar> <http://purl.org/dc/elements/1.1/creator> 'server1/foobar' " +
+        " into <" + testModel + ">;";
+
+    // insert the statement
+    bean.executeQuery(insert);
+
+    // select the statement
+    Answer answer = bean.executeQuery(select);
+    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));
+    assertTrue("Excepting a backup file", file.exists());
+
+    // restore the server
+    bean.restore(file.toURL().openStream(), serverURI);
+
+    // select the statement
+    answer = bean.executeQuery(select);
+    assertTrue("Excepting a answer after restore", answer != null);
+    assertTrue("Excepting a single result and found :" +
+        answer.getRowCount(), (answer.getRowCount() == 3));
+
+  }
+
+  /**
+   * Test the multiple creations of the interpreterbean
+   * Ensure the number of open files are not exceeded on OS.
+   *
+   */
+  public void testMultipleBeanTest() {
+
+    /*
+         // keep a track of the number of session directories
+         String sessionDir = testDir + File.separator +
+                             "server1" + File.separator +
+                             "sessions" + File.separator;
+
+         System.out.println("Session dir is "+ sessionDir );
+
+         // log that we're executing the test
+         log.debug("Starting multiple bean test");
+
+
+         // get the initial number of directories
+         int initNumberOfSessionDirs = (new File(sessionDir)).list().length;
+     log.debug("Initial number of session directories are "+initNumberOfSessionDirs);
+     */
+
+    String query = "select $s $p $o from <rmi://" + hostName +
+        "/server1#> where $s $p $o;";
+
+    // create a 100 beans
+    // TODO: change back to 1000
+    for (int count = 1; count < 100; count++) {
+      ItqlInterpreterBean bean = null;
+      Answer answer = null;
+      try {
+        // create a new bean.
+        bean = new ItqlInterpreterBean();
+
+        log.warn("Starting bean number " + count);
+
+        // execute a basic query
+        answer = bean.executeQuery(query);
+        assertTrue("Failed to query system model", answer.getRowCount() > 0);
+        answer.close();
+
+      } 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 {
+        bean.close();
+      }
+    }
+
+    /*
+         // get the end number of directories
+         int endNumberOfSessionDirs = (new File(sessionDir)).list().length;
+     log.debug("The end number of session directories are "+endNumberOfSessionDirs);
+
+         // the init and end number of directories should be the same
+     assertTrue("Expecting "+initNumberOfSessionDirs+" session to exist, but "+
+               "found "+endNumberOfSessionDirs+" session directories",
+               endNumberOfSessionDirs == initNumberOfSessionDirs);
+     */
+  }
+
+  /**
+   * Test giving ItqlInterpreterBean an explicit session.
+   *
+   * @throws Exception if the test fails
+   */
+  @SuppressWarnings("deprecation")
+  public void testExplicitSession() throws Exception {
+
+    // log that we're executing the test
+    log.debug("Starting explicit session test");
+
+    URI serverURI = new URI("rmi://" + hostName + "/server1");
+    SessionFactory sessionFactory =
+                      SessionFactoryFinder.newSessionFactory(serverURI, true);
+
+    bean.close();
+    bean = new ItqlInterpreterBean(sessionFactory.newSession(),
+                                   sessionFactory.getSecurityDomain());
+
+    // auto-commit = true
+    bean.executeQuery(
+        "insert <es:foo1> <es:bar1> 'foo' into <" + testModel + ">;");
+
+    Answer answer = bean.executeQuery(
+        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
+    assertEquals("Expecting a single result", 1, answer.getRowCount());
+
+    bean.executeQuery(
+        "delete <es:foo1> <es:bar1> 'foo' from <" + testModel + ">;");
+
+    answer = bean.executeQuery(
+        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
+    assertEquals("Expecting no results", 0, answer.getRowCount());
+
+    // explicit tx with commit
+    bean.beginTransaction("explicit-session-test-commit");
+
+    bean.executeQuery(
+        "insert <es:foo1> <es:bar1> 'foo' into <" + testModel + ">;");
+
+    answer = bean.executeQuery(
+        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
+    assertEquals("Expecting a single result", 1, answer.getRowCount());
+
+    bean.executeQuery(
+        "delete <es:foo1> <es:bar1> 'foo' from <" + testModel + ">;");
+
+    bean.commit("explicit-session-test-commit");
+
+    answer = bean.executeQuery(
+        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
+    assertEquals("Expecting no results", 0, answer.getRowCount());
+
+    // explicit tx with rollback
+    bean.beginTransaction("explicit-session-test-rollback");
+
+    bean.executeQuery(
+        "insert <es:foo1> <es:bar1> 'foo' into <" + testModel + ">;");
+
+    answer = bean.executeQuery(
+        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
+    assertEquals("Expecting a single result", 1, answer.getRowCount());
+
+    bean.rollback("explicit-session-test-rollback");
+
+    answer = bean.executeQuery(
+        "select $p $o from <" + testModel + "> " + "where <es:foo1> $p $o;");
+    assertEquals("Expecting no results", 0, answer.getRowCount());
+  }
+
+
+  // ItqlInt
+
+  /**
+   * Initialise members.
+   *
+   * @throws Exception if something goes wrong
+   */
+  protected void setUp() throws Exception {
+
+    bean = new ItqlInterpreterBean();
+  }
+
+  protected void tearDown() throws Exception {
+    if (bean != null) {
+      try {
+        bean.close();
+      } finally {
+        bean = null;
+      }
+    }
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,71 +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;
-
-
-/**
- * Exception thrown by {@link ItqlInterpreter} operations when the query returns
- * an expection.
- *
- * @created 2002-01-10
- *
- * @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
- *      Software Pty Ltd</A>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlInterpreterException extends Exception {
-
-  /**
-   * Constructor for the ItqlInterpreterException object
-   *
-   * @param reason The reason for the exception.
-   */
-  public ItqlInterpreterException(String reason) {
-    super(reason);
-  }
-
-  /**
-   * Constructor for the ItqlInterpreterException object
-   *
-   * @param t The reason for the exception.
-   */
-  public ItqlInterpreterException(Throwable t) {
-    super(t);
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterException.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,71 @@
+/*
+ * 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;
+
+
+/**
+ * Exception thrown by {@link ItqlInterpreter} operations when the query returns
+ * an expection.
+ *
+ * @created 2002-01-10
+ *
+ * @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
+ *      Software Pty Ltd</A>
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class ItqlInterpreterException extends Exception {
+
+  /**
+   * Constructor for the ItqlInterpreterException object
+   *
+   * @param reason The reason for the exception.
+   */
+  public ItqlInterpreterException(String reason) {
+    super(reason);
+  }
+
+  /**
+   * Constructor for the ItqlInterpreterException object
+   *
+   * @param t The reason for the exception.
+   */
+  public ItqlInterpreterException(Throwable t) {
+    super(t);
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,424 +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;
-
-import org.mulgara.query.Answer;
-
-// Java 2 standard packages
-// third party packages
-// third party packages
-import java.io.*;
-import java.util.Random;
-import java.util.Vector;
-
-/**
- * Stress test the system by creating robot itql beans and
- * randomly execute tql queries and record the results
- *
- * Unit test for {@link ItqlInterpreterBean}.
- *
- * @created 2002-06-03
- *
- * @author Tate Jones
- *
- * @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;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 ItqlInterpreterStressTest {
-
-  /**
-   * Description of the Field
-   */
-  private boolean verbose = false;
-
-  /**
-   * Number of repetiions each robot executes the set of tql queries.
-   */
-  private int repetitions = 1000;
-
-  /**
-   * The number of itql bean robots to be created
-   */
-  private int stress = 50;
-
-  /**
-   * The maximum delay between tql executions
-   */
-  private int delay = 7000;
-
-  /**
-   * The minimum delay between tql executions
-   */
-  private int minDelay = 2000;
-
-  /**
-   * Period to wait until another robot is added
-   */
-  private int rampTime = 250;
-
-  /**
-   * The current number of robots active
-   */
-  private int robots = 100;
-
-  /**
-   * The file location of the tql commands
-   */
-  private String itqlLog = "itqlcmd.log";
-
-  /**
-   * The file location of the outputed results for queries
-   */
-  private String queryOutputFile = "query.csv";
-
-  /**
-   * The total time of the stress test
-   */
-  private long totalTime = 0;
-
-  /**
-   * The total number of tql executions across all robots
-   */
-  private long executions = 0;
-
-  /**
-   * Start time of the stress test
-   */
-  private long startTime = 0;
-
-  /**
-   * Used to create random delay between tql executions
-   */
-  private Random rand = new Random();
-
-  /**
-   * Contains the list of queries to be executed
-   */
-  private Vector queries = new Vector();
-
-  /**
-   * Stream to read tql commands
-   */
-  private PrintWriter queryLog = null;
-
-  /**
-   * Stress test the system by creating robot itql beans and
-   * randomly execute tql queries and record the results
-   */
-  public ItqlInterpreterStressTest() {
-
-  }
-
-  /**
-   * METHOD TO DO
-   *
-   * @param args PARAMETER TO DO
-   */
-  public static void main(String[] args) {
-
-    if ( args.length > 0 &&
-        (args[0].equals("-?") ||
-         args[0].equalsIgnoreCase("-h"))) {
-
-      String lineSeparator = System.getProperty("line.separator");
-      String usuage = "Stress test " + lineSeparator + "Usage: "+ lineSeparator +
-          " [-s <number>] [-r <number>] [-w <milliseconds>] "+
-          " [-wm <milliseconds>] [-ra <milliseconds>] [-i <file>] "+
-          " [-o <file>]" + lineSeparator + lineSeparator +
-          " -h display this help screen "+lineSeparator+
-          " -s number of robots to ramp up to (stress level) (default 100)"+lineSeparator+
-          " -r number of query repetitions for each robot to execute (default 1000)"+lineSeparator+
-          " -w the maximum wait time between query executions per robot (default 7000 millisec)"+lineSeparator+
-          " -wm the minimum wait time between query executions per robot (default 2000 millisec)"+lineSeparator+
-          " -ra the ramp time for each new robot to be created (default 250 millisec)"+lineSeparator+
-          " -i the input file containing the itql commands (default itqlcmd.log)"+lineSeparator+
-          " -o output file containing the query performance results (default query.csv)"+lineSeparator;
-      System.out.println( usuage );
-    }
-    else {
-
-      try {
-
-        new ItqlInterpreterStressTest().start(args);
-        System.exit(0);
-      }
-      catch (Exception e) {
-
-        System.out.println(e.getMessage());
-        System.exit(1);
-      }
-    }
-  }
-
-  /**
-   * METHOD TO DO
-   *
-   * @param args PARAMETER TO DO
-   * @throws Exception EXCEPTION TO DO
-   */
-  protected void start(String[] args) throws Exception {
-
-    for (int i = 0; i < args.length; i++) {
-
-      if (args[i].equals("-v")) {
-
-        verbose = true;
-      }
-      else if (args[i].equals("-r")) {
-
-        repetitions = Integer.parseInt(args[i + 1]);
-      }
-      else if (args[i].equals("-s")) {
-
-        stress = Integer.parseInt(args[i + 1]);
-      }
-      else if (args[i].equals("-w")) {
-
-        delay = Integer.parseInt(args[i + 1]);
-      }
-      else if (args[i].equals("-wm")) {
-
-        minDelay = Integer.parseInt(args[i + 1]);
-      }
-      else if (args[i].equals("-i")) {
-
-        itqlLog = args[i + 1];
-      }
-      else if (args[i].equals("-ra")) {
-
-        rampTime = Integer.parseInt(args[i + 1]);
-      }
-      else if (args[i].equals("-o")) {
-
-        queryOutputFile = args[i + 1];
-      }
-
-    }
-
-    // open the itql command log
-    LineNumberReader itqlCommands =
-        new LineNumberReader(new FileReader(itqlLog));
-
-    // read the contents
-    String query = itqlCommands.readLine();
-
-    while (query != null) {
-
-      queries.add(query);
-      query = itqlCommands.readLine();
-    }
-
-    System.out.println("Settings");
-    System.out.println("\tRepetitions :" + repetitions);
-    System.out.println("\tStress (number of robots) :" + stress);
-    System.out.println("\tRandom Delay up-to :" + delay);
-    System.out.println("\tMin. Delay up-to :" + minDelay);
-    System.out.println("\tNumber of queries :" + queries.size());
-    System.out.println("\tRamp robot every :" + rampTime);
-    System.out.println("\tQuery OutputFile :" + queryOutputFile);
-
-    if (queries.size() == 0) {
-
-      System.out.println("No queries to be tested - exiting");
-    }
-
-    if (queryOutputFile == null) {
-
-      System.out.println("The output file has been supplied.  Use -o");
-    }
-
-    queryLog = new PrintWriter(new FileWriter(queryOutputFile), true);
-    queryLog.println("Time\tRobot\tQuery Number\tQuery Time\tAverage Query Time ms" );
-
-    ItqlRobot[] threads = new ItqlRobot[stress];
-
-    for (int i = 0; i < stress; i++) {
-
-      String name = "Robot" + String.valueOf(i);
-      threads[i] = new ItqlRobot(name, queries, repetitions, delay, minDelay);
-    }
-
-    startTime = System.currentTimeMillis();
-
-    for (int i = 0; i < stress; i++) {
-
-      // start a robot
-      System.out.println("Starting " + threads[i].getRobotName());
-      threads[i].start();
-      synchronized (queryLog) {
-        robots++;
-      }
-
-      // wait a period time before adding a new robot
-      try {
-
-        Thread.sleep(rampTime);
-      }
-      catch (InterruptedException e) {
-
-        e.printStackTrace();
-      }
-    }
-
-    System.out.println("All robots have started....");
-
-    for (int i = 0; i < stress; i++) {
-
-      threads[i].join();
-    }
-
-    queryLog.close();
-  }
-
-  private class ItqlRobot extends Thread {
-
-    private ItqlInterpreterBean itql = null;
-    private String name = null;
-    private Vector queries = null;
-    private int repetitions = 0;
-    private int delay = 0;
-    private int minDelay = 0;
-    private int noOfQueries = 0;
-    private boolean verbose = false;
-
-    /**
-     * TQL bean robot that will execute a collection of TQL queries
-     *
-     * @param name robot name identifier
-     * @param queries a list of queries to execute
-     * @param repetitions number of repeatitions
-     * @param delay the maximum delay between executes
-     * @param minDelay the minimum delay between executes
-     */
-    public ItqlRobot(String name, Vector queries, int repetitions, int delay,
-        int minDelay) {
-
-      this.itql = new ItqlInterpreterBean();
-      this.name = name;
-      this.queries = queries;
-      this.repetitions = repetitions;
-      this.delay = delay;
-      this.minDelay = minDelay;
-      this.noOfQueries = queries.size();
-    }
-
-    /**
-     * Obtain the current robot name
-     *
-     * @return String Current robot name
-     */
-
-    public String getRobotName() {
-
-      return this.name;
-    }
-
-    private void executeQuery() {
-
-      Answer answer = null;
-
-      try {
-
-        long start = System.currentTimeMillis();
-        int queryNumber = rand.nextInt(noOfQueries);
-        String query = (String) queries.elementAt(queryNumber);
-        answer = itql.executeQuery(query);
-        if ( answer != null ) {
-          System.out.print(".");
-        } else {
-          System.out.println();
-          System.out.println(query );
-        }
-
-        long queryTime = (System.currentTimeMillis() - start);
-
-        totalTime = totalTime + queryTime;
-        executions++;
-
-        synchronized (queryLog) {
-          queryLog.println(System.currentTimeMillis()+"\t"+
-                           this.getRobotName()+"\t"+
-                           queryNumber + "\t" + queryTime + "\t"+
-                           (totalTime / executions) );
-        }
-      }
-      catch (Exception ex) {
-
-        ex.printStackTrace();
-      }
-      finally {
-        try {
-          answer.close();
-        } catch (Exception ex) {
-          // do nothing
-        }
-      }
-    }
-
-    public void run() {
-
-      try {
-        for (int calls = 0; calls < repetitions; calls++) {
-
-          try {
-
-            this.sleep(rand.nextInt(delay - minDelay) + minDelay);
-          }
-          catch (InterruptedException e) {
-
-            e.printStackTrace();
-          }
-
-          try {
-
-            this.executeQuery();
-          }
-          catch (Exception ex) {
-
-            ex.printStackTrace();
-          }
-        }
-
-        System.out.println(this.name + " has completed");
-      } finally {
-        synchronized (queryLog) {
-          robots--;
-        }
-        itql.close();
-      }
-    }
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlInterpreterStressTest.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,424 @@
+/*
+ * 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;
+
+import org.mulgara.query.Answer;
+
+// Java 2 standard packages
+// third party packages
+// third party packages
+import java.io.*;
+import java.util.Random;
+import java.util.Vector;
+
+/**
+ * Stress test the system by creating robot itql beans and
+ * randomly execute tql queries and record the results
+ *
+ * Unit test for {@link ItqlInterpreterBean}.
+ *
+ * @created 2002-06-03
+ *
+ * @author Tate Jones
+ *
+ * @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;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 ItqlInterpreterStressTest {
+
+  /**
+   * Description of the Field
+   */
+  private boolean verbose = false;
+
+  /**
+   * Number of repetiions each robot executes the set of tql queries.
+   */
+  private int repetitions = 1000;
+
+  /**
+   * The number of itql bean robots to be created
+   */
+  private int stress = 50;
+
+  /**
+   * The maximum delay between tql executions
+   */
+  private int delay = 7000;
+
+  /**
+   * The minimum delay between tql executions
+   */
+  private int minDelay = 2000;
+
+  /**
+   * Period to wait until another robot is added
+   */
+  private int rampTime = 250;
+
+  /**
+   * The current number of robots active
+   */
+  private int robots = 100;
+
+  /**
+   * The file location of the tql commands
+   */
+  private String itqlLog = "itqlcmd.log";
+
+  /**
+   * The file location of the outputed results for queries
+   */
+  private String queryOutputFile = "query.csv";
+
+  /**
+   * The total time of the stress test
+   */
+  private long totalTime = 0;
+
+  /**
+   * The total number of tql executions across all robots
+   */
+  private long executions = 0;
+
+  /**
+   * Start time of the stress test
+   */
+  private long startTime = 0;
+
+  /**
+   * Used to create random delay between tql executions
+   */
+  private Random rand = new Random();
+
+  /**
+   * Contains the list of queries to be executed
+   */
+  private Vector queries = new Vector();
+
+  /**
+   * Stream to read tql commands
+   */
+  private PrintWriter queryLog = null;
+
+  /**
+   * Stress test the system by creating robot itql beans and
+   * randomly execute tql queries and record the results
+   */
+  public ItqlInterpreterStressTest() {
+
+  }
+
+  /**
+   * METHOD TO DO
+   *
+   * @param args PARAMETER TO DO
+   */
+  public static void main(String[] args) {
+
+    if ( args.length > 0 &&
+        (args[0].equals("-?") ||
+         args[0].equalsIgnoreCase("-h"))) {
+
+      String lineSeparator = System.getProperty("line.separator");
+      String usuage = "Stress test " + lineSeparator + "Usage: "+ lineSeparator +
+          " [-s <number>] [-r <number>] [-w <milliseconds>] "+
+          " [-wm <milliseconds>] [-ra <milliseconds>] [-i <file>] "+
+          " [-o <file>]" + lineSeparator + lineSeparator +
+          " -h display this help screen "+lineSeparator+
+          " -s number of robots to ramp up to (stress level) (default 100)"+lineSeparator+
+          " -r number of query repetitions for each robot to execute (default 1000)"+lineSeparator+
+          " -w the maximum wait time between query executions per robot (default 7000 millisec)"+lineSeparator+
+          " -wm the minimum wait time between query executions per robot (default 2000 millisec)"+lineSeparator+
+          " -ra the ramp time for each new robot to be created (default 250 millisec)"+lineSeparator+
+          " -i the input file containing the itql commands (default itqlcmd.log)"+lineSeparator+
+          " -o output file containing the query performance results (default query.csv)"+lineSeparator;
+      System.out.println( usuage );
+    }
+    else {
+
+      try {
+
+        new ItqlInterpreterStressTest().start(args);
+        System.exit(0);
+      }
+      catch (Exception e) {
+
+        System.out.println(e.getMessage());
+        System.exit(1);
+      }
+    }
+  }
+
+  /**
+   * METHOD TO DO
+   *
+   * @param args PARAMETER TO DO
+   * @throws Exception EXCEPTION TO DO
+   */
+  protected void start(String[] args) throws Exception {
+
+    for (int i = 0; i < args.length; i++) {
+
+      if (args[i].equals("-v")) {
+
+        verbose = true;
+      }
+      else if (args[i].equals("-r")) {
+
+        repetitions = Integer.parseInt(args[i + 1]);
+      }
+      else if (args[i].equals("-s")) {
+
+        stress = Integer.parseInt(args[i + 1]);
+      }
+      else if (args[i].equals("-w")) {
+
+        delay = Integer.parseInt(args[i + 1]);
+      }
+      else if (args[i].equals("-wm")) {
+
+        minDelay = Integer.parseInt(args[i + 1]);
+      }
+      else if (args[i].equals("-i")) {
+
+        itqlLog = args[i + 1];
+      }
+      else if (args[i].equals("-ra")) {
+
+        rampTime = Integer.parseInt(args[i + 1]);
+      }
+      else if (args[i].equals("-o")) {
+
+        queryOutputFile = args[i + 1];
+      }
+
+    }
+
+    // open the itql command log
+    LineNumberReader itqlCommands =
+        new LineNumberReader(new FileReader(itqlLog));
+
+    // read the contents
+    String query = itqlCommands.readLine();
+
+    while (query != null) {
+
+      queries.add(query);
+      query = itqlCommands.readLine();
+    }
+
+    System.out.println("Settings");
+    System.out.println("\tRepetitions :" + repetitions);
+    System.out.println("\tStress (number of robots) :" + stress);
+    System.out.println("\tRandom Delay up-to :" + delay);
+    System.out.println("\tMin. Delay up-to :" + minDelay);
+    System.out.println("\tNumber of queries :" + queries.size());
+    System.out.println("\tRamp robot every :" + rampTime);
+    System.out.println("\tQuery OutputFile :" + queryOutputFile);
+
+    if (queries.size() == 0) {
+
+      System.out.println("No queries to be tested - exiting");
+    }
+
+    if (queryOutputFile == null) {
+
+      System.out.println("The output file has been supplied.  Use -o");
+    }
+
+    queryLog = new PrintWriter(new FileWriter(queryOutputFile), true);
+    queryLog.println("Time\tRobot\tQuery Number\tQuery Time\tAverage Query Time ms" );
+
+    ItqlRobot[] threads = new ItqlRobot[stress];
+
+    for (int i = 0; i < stress; i++) {
+
+      String name = "Robot" + String.valueOf(i);
+      threads[i] = new ItqlRobot(name, queries, repetitions, delay, minDelay);
+    }
+
+    startTime = System.currentTimeMillis();
+
+    for (int i = 0; i < stress; i++) {
+
+      // start a robot
+      System.out.println("Starting " + threads[i].getRobotName());
+      threads[i].start();
+      synchronized (queryLog) {
+        robots++;
+      }
+
+      // wait a period time before adding a new robot
+      try {
+
+        Thread.sleep(rampTime);
+      }
+      catch (InterruptedException e) {
+
+        e.printStackTrace();
+      }
+    }
+
+    System.out.println("All robots have started....");
+
+    for (int i = 0; i < stress; i++) {
+
+      threads[i].join();
+    }
+
+    queryLog.close();
+  }
+
+  private class ItqlRobot extends Thread {
+
+    private ItqlInterpreterBean itql = null;
+    private String name = null;
+    private Vector queries = null;
+    private int repetitions = 0;
+    private int delay = 0;
+    private int minDelay = 0;
+    private int noOfQueries = 0;
+    private boolean verbose = false;
+
+    /**
+     * TQL bean robot that will execute a collection of TQL queries
+     *
+     * @param name robot name identifier
+     * @param queries a list of queries to execute
+     * @param repetitions number of repeatitions
+     * @param delay the maximum delay between executes
+     * @param minDelay the minimum delay between executes
+     */
+    public ItqlRobot(String name, Vector queries, int repetitions, int delay,
+        int minDelay) {
+
+      this.itql = new ItqlInterpreterBean();
+      this.name = name;
+      this.queries = queries;
+      this.repetitions = repetitions;
+      this.delay = delay;
+      this.minDelay = minDelay;
+      this.noOfQueries = queries.size();
+    }
+
+    /**
+     * Obtain the current robot name
+     *
+     * @return String Current robot name
+     */
+
+    public String getRobotName() {
+
+      return this.name;
+    }
+
+    private void executeQuery() {
+
+      Answer answer = null;
+
+      try {
+
+        long start = System.currentTimeMillis();
+        int queryNumber = rand.nextInt(noOfQueries);
+        String query = (String) queries.elementAt(queryNumber);
+        answer = itql.executeQuery(query);
+        if ( answer != null ) {
+          System.out.print(".");
+        } else {
+          System.out.println();
+          System.out.println(query );
+        }
+
+        long queryTime = (System.currentTimeMillis() - start);
+
+        totalTime = totalTime + queryTime;
+        executions++;
+
+        synchronized (queryLog) {
+          queryLog.println(System.currentTimeMillis()+"\t"+
+                           this.getRobotName()+"\t"+
+                           queryNumber + "\t" + queryTime + "\t"+
+                           (totalTime / executions) );
+        }
+      }
+      catch (Exception ex) {
+
+        ex.printStackTrace();
+      }
+      finally {
+        try {
+          answer.close();
+        } catch (Exception ex) {
+          // do nothing
+        }
+      }
+    }
+
+    public void run() {
+
+      try {
+        for (int calls = 0; calls < repetitions; calls++) {
+
+          try {
+
+            this.sleep(rand.nextInt(delay - minDelay) + minDelay);
+          }
+          catch (InterruptedException e) {
+
+            e.printStackTrace();
+          }
+
+          try {
+
+            this.executeQuery();
+          }
+          catch (Exception ex) {
+
+            ex.printStackTrace();
+          }
+        }
+
+        System.out.println(this.name + " has completed");
+      } finally {
+        synchronized (queryLog) {
+          robots--;
+        }
+        itql.close();
+      }
+    }
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,289 +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 jargs.gnu.CmdLineParser;
-
-// third party packages
-import org.apache.log4j.Logger;
-
-/**
- * Command line option parser for the iTQL interpreter.
- *
- * @created 2001-09-20
- *
- * @author Tom Adams
- *
- * @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;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 ItqlOptionParser extends CmdLineParser {
-
-  /**
-   * option to dump the entire interpreter configuration
-   */
-  public final static Option DUMP_CONFIG =
-      new CmdLineParser.Option.StringOption('d', "dumpconfig");
-
-  /**
-   * option to display the gui
-   */
-  public final static Option GUI =
-      new CmdLineParser.Option.BooleanOption('g', "gui");
-
-  /**
-   * option to display the help
-   */
-  public final static Option HELP =
-      new CmdLineParser.Option.BooleanOption('h', "help");
-
-  /**
-   * option to use an external configuration file
-   */
-  public final static Option ITQL_CONFIG =
-      new CmdLineParser.Option.StringOption('i', "itqlconfig");
-
-  /**
-   * option to use an external logging configuration file
-   */
-  public final static Option LOG_CONFIG =
-      new CmdLineParser.Option.StringOption('l', "logconfig");
-
-  /**
-   * option to turn off default pre- and post-loading scripts
-   */
-  public final static Option NO_LOAD =
-      new CmdLineParser.Option.BooleanOption('n', "noload");
-
-  /**
-   * option to change the post-loading script
-   */
-  public final static Option POST_SCRIPT =
-      new CmdLineParser.Option.StringOption('o', "postload");
-
-  /**
-   * option to change the pre-loading script
-   */
-  public final static Option PRE_SCRIPT =
-      new CmdLineParser.Option.StringOption('p', "preload");
-
-  /**
-   * option to execute an iTQL script
-   */
-  public final static Option SCRIPT =
-      new CmdLineParser.Option.StringOption('s', "script");
-
-  //
-  // Constants
-  //
-
-  /**
-   * the category to log to
-   */
-  private final static Logger log = Logger.getLogger(ItqlOptionParser.class);
-
-  //
-  // members
-  //
-
-  /**
-   * the command line arguments passed to the itql interpreter
-   */
-  private String[] args = null;
-
-  /**
-   * flag indicating whether we've parsed the options yet
-   */
-  private boolean optionsParsed = false;
-
-  //
-  // Constructors
-  //
-
-  /**
-   * Creates a new iTQL command line option parser to parse the command line
-   * <code>args</code> given.
-   *
-   * @param args the command line arguments
-   */
-  public ItqlOptionParser(String[] args) {
-
-    // call the superclass constructor
-    super();
-
-    // validate args parameter
-    if (args == null) {
-
-      throw new IllegalArgumentException("Null \"args\" parameter");
-    }
-
-    // end if
-    // log that we've created a parser
-    log.debug("Created option parser for iTQL interpreter");
-
-    // set the member
-    this.setArgs(args);
-
-    // add the options
-    this.addOption(HELP);
-
-    this.addOption(NO_LOAD);
-    this.addOption(POST_SCRIPT);
-    this.addOption(PRE_SCRIPT);
-    this.addOption(LOG_CONFIG);
-    this.addOption(SCRIPT);
-  }
-
-  // ItqlOptionParser()
-  //
-  // Public API
-  //
-
-  /**
-   * Parses the command line arguments given to this parser.
-   *
-   * @throws UnknownOptionException if an unknown option was specified in the
-   *      list of options given to the parser
-   * @throws IllegalOptionValueException if an option given to the parser
-   *      contains an illegal value
-   */
-  public void parse() throws UnknownOptionException,
-      IllegalOptionValueException {
-
-    // log that
-    log.debug("Parsing iTQL interpreter arguments");
-
-    // parse the arguments if we haven't done so already
-    if (!this.optionsParsed) {
-
-      // parse the arguments
-      this.parse(this.getArgs());
-
-      // fail if there are any remaing that we dodn't know about
-      String[] remainingArgs = this.getRemainingArgs();
-
-      if (remainingArgs.length > 0) {
-
-        // throw a new exception to indicate that there were unkown arguments
-        throw new UnknownOptionException(remainingArgs[0]);
-      }
-
-      // end if
-      // we've now parser the options
-      this.optionsParsed = true;
-    }
-
-    // end if
-  }
-
-  // parse()
-
-  /**
-   * Validates the command line options.
-   *
-   * @return true if the options are valid
-   */
-  public boolean optionsValid() {
-
-    boolean optionsValid = false;
-
-    try {
-
-      // validate params by parsing the arguments
-      this.parse();
-      optionsValid = true;
-    }
-    catch (UnknownOptionException uoe) {
-
-      optionsValid = false;
-    }
-    catch (IllegalOptionValueException iove) {
-
-      optionsValid = false;
-    }
-
-    // try-catch
-    // return whether the options are valid
-    return optionsValid;
-  }
-
-  // optionsValid()
-
-  /*
-   CmdLineParser.Option[] allOptions =
-    new CmdLineParser.Option[] { MyOptionsParser.VERBOSE,
-                                MyOptionsParser.NAME,
-                                MyOptionsParser.SIZE };
-   for ( int j = 0; j<allOptions.length; ++j ) {
-    System.out.println(allOptions[j].longForm() + ": " +
-                      myOptions.getOptionValue(allOptions[j]));
-   }
-   String[] otherArgs = myOptions.getRemainingArgs();
-   System.out.println("remaining args: ");
-   for ( int i = 0; i<otherArgs.length; ++i ) {
-    System.out.println(otherArgs[i]);
-   }
-   */
-
-  //
-  // Internal methods
-  //
-
-  /**
-   * Sets the command line arguments passed to the itql interpreter.
-   *
-   * @param args The new Args value
-   */
-  private void setArgs(String[] args) {
-
-    this.args = args;
-  }
-
-  // setArgs()
-
-  /**
-   * Returns the command line arguments passed to the itql interpreter.
-   *
-   * @return the command line arguments passed to the itql interpreter
-   */
-  private String[] getArgs() {
-
-    return this.args;
-  }
-
-  // getArgs()
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlOptionParser.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,289 @@
+/*
+ * 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 jargs.gnu.CmdLineParser;
+
+// third party packages
+import org.apache.log4j.Logger;
+
+/**
+ * Command line option parser for the iTQL interpreter.
+ *
+ * @created 2001-09-20
+ *
+ * @author Tom Adams
+ *
+ * @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;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 ItqlOptionParser extends CmdLineParser {
+
+  /**
+   * option to dump the entire interpreter configuration
+   */
+  public final static Option DUMP_CONFIG =
+      new CmdLineParser.Option.StringOption('d', "dumpconfig");
+
+  /**
+   * option to display the gui
+   */
+  public final static Option GUI =
+      new CmdLineParser.Option.BooleanOption('g', "gui");
+
+  /**
+   * option to display the help
+   */
+  public final static Option HELP =
+      new CmdLineParser.Option.BooleanOption('h', "help");
+
+  /**
+   * option to use an external configuration file
+   */
+  public final static Option ITQL_CONFIG =
+      new CmdLineParser.Option.StringOption('i', "itqlconfig");
+
+  /**
+   * option to use an external logging configuration file
+   */
+  public final static Option LOG_CONFIG =
+      new CmdLineParser.Option.StringOption('l', "logconfig");
+
+  /**
+   * option to turn off default pre- and post-loading scripts
+   */
+  public final static Option NO_LOAD =
+      new CmdLineParser.Option.BooleanOption('n', "noload");
+
+  /**
+   * option to change the post-loading script
+   */
+  public final static Option POST_SCRIPT =
+      new CmdLineParser.Option.StringOption('o', "postload");
+
+  /**
+   * option to change the pre-loading script
+   */
+  public final static Option PRE_SCRIPT =
+      new CmdLineParser.Option.StringOption('p', "preload");
+
+  /**
+   * option to execute an iTQL script
+   */
+  public final static Option SCRIPT =
+      new CmdLineParser.Option.StringOption('s', "script");
+
+  //
+  // Constants
+  //
+
+  /**
+   * the category to log to
+   */
+  private final static Logger log = Logger.getLogger(ItqlOptionParser.class);
+
+  //
+  // members
+  //
+
+  /**
+   * the command line arguments passed to the itql interpreter
+   */
+  private String[] args = null;
+
+  /**
+   * flag indicating whether we've parsed the options yet
+   */
+  private boolean optionsParsed = false;
+
+  //
+  // Constructors
+  //
+
+  /**
+   * Creates a new iTQL command line option parser to parse the command line
+   * <code>args</code> given.
+   *
+   * @param args the command line arguments
+   */
+  public ItqlOptionParser(String[] args) {
+
+    // call the superclass constructor
+    super();
+
+    // validate args parameter
+    if (args == null) {
+
+      throw new IllegalArgumentException("Null \"args\" parameter");
+    }
+
+    // end if
+    // log that we've created a parser
+    log.debug("Created option parser for iTQL interpreter");
+
+    // set the member
+    this.setArgs(args);
+
+    // add the options
+    this.addOption(HELP);
+
+    this.addOption(NO_LOAD);
+    this.addOption(POST_SCRIPT);
+    this.addOption(PRE_SCRIPT);
+    this.addOption(LOG_CONFIG);
+    this.addOption(SCRIPT);
+  }
+
+  // ItqlOptionParser()
+  //
+  // Public API
+  //
+
+  /**
+   * Parses the command line arguments given to this parser.
+   *
+   * @throws UnknownOptionException if an unknown option was specified in the
+   *      list of options given to the parser
+   * @throws IllegalOptionValueException if an option given to the parser
+   *      contains an illegal value
+   */
+  public void parse() throws UnknownOptionException,
+      IllegalOptionValueException {
+
+    // log that
+    log.debug("Parsing iTQL interpreter arguments");
+
+    // parse the arguments if we haven't done so already
+    if (!this.optionsParsed) {
+
+      // parse the arguments
+      this.parse(this.getArgs());
+
+      // fail if there are any remaing that we dodn't know about
+      String[] remainingArgs = this.getRemainingArgs();
+
+      if (remainingArgs.length > 0) {
+
+        // throw a new exception to indicate that there were unkown arguments
+        throw new UnknownOptionException(remainingArgs[0]);
+      }
+
+      // end if
+      // we've now parser the options
+      this.optionsParsed = true;
+    }
+
+    // end if
+  }
+
+  // parse()
+
+  /**
+   * Validates the command line options.
+   *
+   * @return true if the options are valid
+   */
+  public boolean optionsValid() {
+
+    boolean optionsValid = false;
+
+    try {
+
+      // validate params by parsing the arguments
+      this.parse();
+      optionsValid = true;
+    }
+    catch (UnknownOptionException uoe) {
+
+      optionsValid = false;
+    }
+    catch (IllegalOptionValueException iove) {
+
+      optionsValid = false;
+    }
+
+    // try-catch
+    // return whether the options are valid
+    return optionsValid;
+  }
+
+  // optionsValid()
+
+  /*
+   CmdLineParser.Option[] allOptions =
+    new CmdLineParser.Option[] { MyOptionsParser.VERBOSE,
+                                MyOptionsParser.NAME,
+                                MyOptionsParser.SIZE };
+   for ( int j = 0; j<allOptions.length; ++j ) {
+    System.out.println(allOptions[j].longForm() + ": " +
+                      myOptions.getOptionValue(allOptions[j]));
+   }
+   String[] otherArgs = myOptions.getRemainingArgs();
+   System.out.println("remaining args: ");
+   for ( int i = 0; i<otherArgs.length; ++i ) {
+    System.out.println(otherArgs[i]);
+   }
+   */
+
+  //
+  // Internal methods
+  //
+
+  /**
+   * Sets the command line arguments passed to the itql interpreter.
+   *
+   * @param args The new Args value
+   */
+  private void setArgs(String[] args) {
+
+    this.args = args;
+  }
+
+  // setArgs()
+
+  /**
+   * Returns the command line arguments passed to the itql interpreter.
+   *
+   * @return the command line arguments passed to the itql interpreter
+   */
+  private String[] getArgs() {
+
+    return this.args;
+  }
+
+  // getArgs()
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,980 +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;
-
-// Java 2 standard packages
-import java.io.*;
-import java.net.*;
-import java.util.*;
-
-import javax.xml.parsers.*;
-
-// Third party packages
-import org.apache.log4j.BasicConfigurator;
-import org.apache.log4j.Logger;
-import org.apache.log4j.xml.DOMConfigurator;
-
-// Automatically generated packages (SableCC)
-import org.mulgara.itql.analysis.DepthFirstAdapter;
-import org.mulgara.itql.lexer.Lexer;
-import org.mulgara.itql.lexer.LexerException;
-import org.mulgara.itql.node.*;
-import org.mulgara.itql.parser.Parser;
-import org.mulgara.itql.parser.ParserException;
-import org.mulgara.query.Answer;
-import org.mulgara.query.QueryException;
-import org.mulgara.query.TuplesException;
-
-import javax.swing.*;
-
-/**
- * Interactive TQL session command line shell.
- *
- * @created 2001-Aug-17
- *
- * @author Simon Raboczi
- * @author Tom Adams
- * @author Andrew Newman
- *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:15 $ by $Author: newmana $
- *
- * @maintenanceAuthor $Author: newmana $
- *
- * @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 ItqlSession {
-
-  /**
-   * Get line separator.
-   */
-  private static final String eol = System.getProperty("line.separator");
-
-  /**
-   * The prompt.
-   */
-  public final static String PROMPT = "iTQL> ";
-
-  /**
-   * The secondary prompt, indicating an incomplete command.
-   */
-  public final static String PROMPT2 = "      ";
-
-  //
-  // Constants
-  //
-
-  /**
-   * the log4j configuration file path (withing the JAR file)
-   */
-  private final static String LOG4J_CONFIG_PATH = "log4j-itql.xml";
-
-  /**
-   * the logging category to log to
-   */
-  private final static Logger log = Logger.getLogger(ItqlSession.class);
-
-  /**
-   * the default path to the pre-loading script
-   */
-  private final static String PRE_LOADING_SCRIPT_PATH = "default-pre.itql";
-
-  /**
-   * the default path to the post-loading script
-   */
-  private final static String POST_LOADING_SCRIPT_PATH = "default-post.itql";
-
-  //
-  // Private state
-  //
-
-  /**
-   * The graphical UI.
-   */
-  private static ItqlSessionUI ui;
-
-  /**
-   * The messages from the previous queries.
-   */
-  private List messages = new ArrayList();
-
-  /**
-   * The answers from the previous queries.
-   */
-  private List answers = new ArrayList();
-
-  /**
-   * The file name (URL) of the script to execute if -s is given.
-   */
-  private String script = null;
-
-  //
-  // Members
-  //
-
-  /**
-   * the iTQL interpreter associated with this session
-   */
-  private final ItqlInterpreterBean itqlBean;
-
-  /**
-   * the URL of the post-loading script
-   */
-  private URL postLoadingScriptURL = null;
-
-  /**
-   * the URL of the pre-loading script
-   */
-  private URL preLoadingScriptURL = null;
-
-  //
-  // Constructors
-  //
-
-  /**
-   * Creates a new ITQL session.
-   *
-   * @throws IOException if the logging configuration can't be read
-   * @throws QueryException if a connection can't be established
-   *   to the server
-   */
-  public ItqlSession() throws IOException, QueryException {
-
-    // load the default logging configuration
-    this.loadLoggingConfig();
-
-    itqlBean = new ItqlInterpreterBean();
-  }
-
-  /**
-   * 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
-   */
-  public static void session(ItqlSession session, InputStream in,
-      PrintStream out) {
-
-    // ui.print("@@build.label@@" + eol);
-
-    // display the copyright notice
-    ui.print("iTQL Command Line Interface" + eol +
-        "Copyright (C) 2001-2004 Tucana Technologies, Inc." + eol);
-
-    // print a help message
-    ui.print(eol + "Type \"help ;\", then enter for help." + eol + eol);
-
-    // print a prompt
-    ui.print(PROMPT);
-  }
-
-  /**
-   * Start an interactive TQL session.
-   *
-   * @param args command line parameters
-   * @throws IOException EXCEPTION TO DO
-   * @throws QueryException EXCEPTION TO DO
-   */
-  public static void main(String[] args) throws IOException, QueryException {
-
-    // create a new session to work with
-    ItqlSession itqlSession = new ItqlSession();
-
-    try {
-
-      // set the default pre- and post-loading scripts
-      itqlSession.retrieveDefaultLoadingScripts();
-
-      // create a parser to parse the command line options
-      ItqlOptionParser optsParser = new ItqlOptionParser(args);
-
-      // parse the
-      optsParser.parse();
-
-      // process the options
-      boolean startSession = itqlSession.processOptions(optsParser);
-
-      // log that we've processed the options
-      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
-      itqlSession.executeLoadingScript(itqlSession.getPreLoadingScriptURL());
-
-      if (itqlSession.getScript() != null) {
-
-        itqlSession.executeScript(new URL(itqlSession.getScript()));
-
-      } // end if
-
-      // log that we've executed the pre-loading script
-      if (log.isDebugEnabled()) {
-
-        log.debug("Executed pre-loading script");
-      }
-
-      // if we can, execute this session using std in and std out
-      if (startSession) {
-
-        // Create the UI.
-        JFrame app = new JFrame("iTQL Shell");
-        app.setSize(640, 480);
-        app.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
-        ui = new ItqlSessionUI(itqlSession);
-        app.getContentPane().add(ui);
-
-        if (log.isInfoEnabled()) {
-
-          log.info("Starting iTQL interpreter");
-        }
-
-        ItqlSession.session(itqlSession, System.in, System.out);
-
-        // Make the UI visible
-        app.setVisible(true);
-
-        if (log.isInfoEnabled()) {
-
-          log.info("Stopping iTQL interpreter");
-        }
-
-        // log that we've executed the pre-loading script
-        if (log.isDebugEnabled()) {
-
-          log.debug("Executed post-loading script");
-        }
-      } else {
-
-        // execute the post-loading script
-        itqlSession.executeLoadingScript(itqlSession.getPostLoadingScriptURL());
-
-        // Close the session and exit.
-        itqlSession.close();
-        System.exit(0);
-      }
-    } catch (ItqlOptionParser.UnknownOptionException uoe) {
-
-      // log that the option we received was invalid
-      log.warn("Invalid command line option specified: " + uoe.getOptionName());
-
-      // let the user know about the invalid option
-      System.err.println("Invalid option: " + uoe.getOptionName());
-
-      // print the usage instructions
-      itqlSession.printUsage();
-    } catch (ItqlOptionParser.IllegalOptionValueException iove) {
-
-      // format the incorrect option string
-      String optionMsg =
-          "-" + iove.getOption().shortForm() + ", --" +
-          iove.getOption().longForm() + " = " + iove.getValue();
-
-      // log that the option value we received was invalid
-      log.warn("Invalid command line option value specified: " + optionMsg);
-
-      // let the user know about the invalid option
-      System.err.println("Invalid option value: " + optionMsg);
-
-      // print the usage instructions
-      itqlSession.printUsage();
-    }
-  }
-
-  // ItqlSession()
-  //
-  // Methods overriding the AbstractSession superclass
-  //
-
-  /**
-   * 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 the message from the execution of the last command.
-   */
-  public List getLastMessages() {
-
-    return messages;
-  }
-
-  /**
-   * Returns a list of Answers from the execution of the last command or series
-   * of commands.  Failures will have null answers in place.
-   */
-  public List getLastAnswers() {
-
-    return answers;
-  }
-
-  /**
-   * Returns the script to run.
-   *
-   * @return the script to run.
-   */
-  public String getScript() {
-
-    return script;
-  }
-
-  /**
-   * Executes a series of commands the given command.  Makes the result availabe
-   * via getLastMessages and getLastAnswers.
-   *
-   * @param command the command to execute
-   */
-  public void executeCommand(String command) {
-
-    // Reset answers and messages
-    answers.clear();
-    messages.clear();
-
-    String message = null;
-    Answer answer = null;
-    String[] queries = ItqlInterpreterBean.splitQuery(command);
-
-    for (int index = 0; index < queries.length; index++) {
-
-      try {
-
-        // log the command we're executing
-        if (log.isDebugEnabled()) {
-
-          log.debug("Starting execution of command \"" + command + "\"");
-        }
-
-        // execute the command
-        answer = itqlBean.executeQuery(queries[index]);
-
-        // close the session if requested
-        if (itqlBean.isQuitRequested()) {
-
-          close();
-        }
-
-        message = itqlBean.getLastMessage();
-
-        // log that we've executed the command
-        if (log.isDebugEnabled()) {
-
-          log.debug("Completed execution of commmand \"" + command + "\"");
-        }
-      } catch (UnsupportedOperationException uoe) {
-
-        // Known exception get the last message.
-        message = itqlBean.getLastMessage();
-        log.warn("Couldn't execute command", uoe);
-      } catch (ItqlInterpreterException iee) {
-
-        // Known exception get the last message.
-        message = itqlBean.getLastMessage();
-        log.warn("Couldn't execute command", iee);
-      } catch (Exception e) {
-
-        // Unknown exception get the exception's message.
-        message = e.getMessage();
-        log.error("Couldn't execute command", e);
-      } catch (Error e) {
-
-        // Unknown exception get the exception's message.
-        message = e.getMessage();
-        log.error("Couldn't execute command", e);
-      }
-
-      // Add the message and answer
-      messages.add(message);
-      answers.add(answer);
-    }
-  }
-
-  /**
-   * Sets the URL of the pre-loading script.
-   *
-   * @param preLoadingScriptURL the URL of the pre-loading script
-   */
-  private void setPreLoadingScriptURL(URL preLoadingScriptURL) {
-
-    this.preLoadingScriptURL = preLoadingScriptURL;
-  }
-
-  // getPreLoadingScriptURL()
-
-  /**
-   * Sets the URL of the post-loading script.
-   *
-   * @param postLoadingScriptURL the URL of the post-loading script
-   */
-  private void setPostLoadingScriptURL(URL postLoadingScriptURL) {
-
-    this.postLoadingScriptURL = postLoadingScriptURL;
-  }
-
-  // setInterpreter()
-
-  /**
-   * Returns the URL of the pre-loading script.
-   *
-   * @return the URL of the pre-loading script
-   */
-  private URL getPreLoadingScriptURL() {
-
-    return this.preLoadingScriptURL;
-  }
-
-  // setPostLoadingScriptURL()
-
-  /**
-   * Returns the URL of the post-loading script.
-   *
-   * @return the URL of the post-loading script
-   */
-  private URL getPostLoadingScriptURL() {
-
-    return this.postLoadingScriptURL;
-  }
-
-  // command()
-
-  /**
-   * Closes the session associated with this interpreter. Subclasses that
-   * override this method <strong>must</strong> call <code>super.close()</code>.
-   */
-  private void close() {
-
-    // Close the session, if any
-    itqlBean.setServerURI(null);
-    itqlBean.close();
-
-    // Exit program
-    System.exit(0);
-  }
-
-  // main()
-  //
-  // Internal methods
-  //
-
-  /**
-   * Retrieves the default loading scripts.
-   */
-  private void retrieveDefaultLoadingScripts() {
-
-    // locate the pre-loading script
-    URL preScriptURL = this.locateScript(PRE_LOADING_SCRIPT_PATH);
-
-    if (preScriptURL != null) {
-
-      this.setPreLoadingScriptURL(preScriptURL);
-    }
-
-    // locate the post-loading script
-    URL postScriptURL = this.locateScript(POST_LOADING_SCRIPT_PATH);
-
-    if (postScriptURL != null) {
-
-      this.setPostLoadingScriptURL(postScriptURL);
-    }
-  }
-
-  /**
-   * Locates the loading script with the given path. <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, null 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;
-    }
-
-    // end if
-    // log that we're looking for scripts
-    log.debug("Looking for script " + scriptPath + " in " + currentDirectory);
-
-    // try to find the script
-    File loadingScript = new File(currentDirectory + scriptPath);
-
-    if (loadingScript.exists() && loadingScript.isFile()) {
-
-      // log that we've found the file
-      log.debug("Found loading script - " + loadingScript);
-
-      // return the URL!!!
-      try {
-
-        scriptURL = loadingScript.toURL();
-      } catch (MalformedURLException mue) {
-
-        // log the error
-        log.warn("Unable to convert loading script filename to URL - " +
-            mue.getMessage());
-        System.err.println("Unable to convert loading script filename " +
-            "to URL - " + loadingScript);
-      }
-
-      // try-catch
-    } else {
-
-      // log that we're now looking in the classpath
-      log.debug("Looking for loading script " + scriptPath + " in classpath");
-
-      // try to obtain from the classpath
-      URL loadingScriptURL = ClassLoader.getSystemResource(scriptPath);
-
-      // set it
-      if (loadingScriptURL != null) {
-
-        log.debug("Found loading script at - " + loadingScriptURL);
-        scriptURL = loadingScriptURL;
-      }
-
-      // end if
-    }
-
-    // end if
-    // return the URL
-    return scriptURL;
-  }
-
-  // locateScript()
-
-  /**
-   * Executes the pre-loading script.
-   *
-   * @param loadingScriptURL the URL of the loading (pre/post) script to execute
-   */
-  private void executeLoadingScript(URL loadingScriptURL) {
-
-    // execute it
-    if (loadingScriptURL != null) {
-
-      // log that we're executing the script
-      log.debug("Executing loading script " + loadingScriptURL);
-
-      // execute the script
-      this.executeScript(loadingScriptURL);
-    }
-
-    // end if
-  }
-
-  // executeLoadingScript()
-
-  /**
-   * 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 RETURNED VALUE TO DO
-   */
-  private boolean processOptions(ItqlOptionParser parser) {
-
-    // log that we're processing command line options
-    log.debug("Processing command line options");
-
-    // flag to indicate whether we can start the interpreter
-    boolean startInterpreter = true;
-
-    try {
-
-      // find out if the user wants help
-      if (parser.getOptionValue(ItqlOptionParser.HELP) != null) {
-
-        // print the help
-        this.printUsage();
-
-        // don't start the interpreter
-        startInterpreter = false;
-      } else {
-
-        // dump the interpreter configuration
-        Object dumpConfig = parser.getOptionValue(ItqlOptionParser.DUMP_CONFIG);
-
-        if (dumpConfig != null) {
-
-          this.dumpConfig();
-        }
-
-        // end if
-        // load an external interpreter configuration file
-        Object itqlConf = parser.getOptionValue(ItqlOptionParser.ITQL_CONFIG);
-
-        if (itqlConf != null) {
-
-          this.loadItqlConfig(new URL( (String) itqlConf));
-        }
-
-        // end if
-        // load an external logging configuration file
-        Object logConf = parser.getOptionValue(ItqlOptionParser.LOG_CONFIG);
-
-        if (logConf != null) {
-
-          this.loadLoggingConfig(new URL( (String) logConf));
-        }
-
-        // end if
-        // find out whether to execute pre-and post loading scripts
-        Object defaultLoadingScripts =
-            parser.getOptionValue(ItqlOptionParser.NO_LOAD);
-
-        if (defaultLoadingScripts == null) {
-
-          // override the default pre-loading script
-          Object preScript = parser.getOptionValue(ItqlOptionParser.PRE_SCRIPT);
-
-          if (preScript != null) {
-
-            this.setPreLoadingScriptURL(new URL( (String) preScript));
-          }
-
-          // end if
-          // override the default post-loading script
-          Object postScript =
-              parser.getOptionValue(ItqlOptionParser.POST_SCRIPT);
-
-          if (postScript != null) {
-
-            this.setPostLoadingScriptURL(new URL( (String) preScript));
-          }
-
-          // end if
-        } else {
-
-          // log that we've turned off pre- and post-loading scripts
-          log.debug("Pre- and post-loading scripts disabled");
-
-          // unset default pre- and post-loading scripts
-          this.setPreLoadingScriptURL(null);
-          this.setPostLoadingScriptURL(null);
-        }
-
-        // execute an iTQL script and quit
-        script = (String) parser.getOptionValue(ItqlOptionParser.SCRIPT);
-
-        if (script != null) {
-
-          startInterpreter = false;
-
-        } // end if
-
-      } // end if
-    } catch (IOException ioe) {
-
-      // log the error
-      log.warn("Invalid URL on command line - " + ioe.getMessage());
-
-      // print the usage
-      System.err.println("Invalid URL - " + ioe.getMessage());
-      this.printUsage();
-
-      // don't start the interpreter
-      startInterpreter = false;
-    } catch (Exception e) {
-
-      // log the error
-      log.warn("Could not start interpreter - " + e.getMessage());
-
-      // let the user know
-      System.err.println("Error - " + e.getMessage());
-
-      // don't start the interpreter
-      startInterpreter = false;
-    }
-
-    // try-catch
-    // return the continue flag
-    return startInterpreter;
-  }
-
-  // processOptions()
-
-  /**
-   * Prints the usage instructions for the interpreter.
-   */
-  private void printUsage() {
-
-    // build the usage message
-    StringBuffer usage = new StringBuffer();
-    usage.append("Usage: java -jar <jarfile> ");
-
-    //usage.append("[-d|");
-    //usage.append("-g|");
-    //usage.append("-h] ");
-    usage.append("[-h|");
-    usage.append("-n] ");
-
-    //usage.append("[-i <url>] ");
-    usage.append("[-l <url>] ");
-    usage.append("[-o <url>] ");
-    usage.append("[-p <url>] ");
-    usage.append("[-s <url>]");
-    usage.append(eol);
-    usage.append(eol);
-
-    //usage.append("-d, --dumpconfig    dump the interpreter configuration to " +
-    //    "the current directory\n");
-    //usage.append("-g, --gui           display the iTQL GUI  ");
-    usage.append("-h, --help          display this help screen" + eol);
-    usage.append("-n, --noload        do not execute pre- and post-loading " +
-        "scripts (useful with -s)" + eol);
-
-    //usage.append("-i, --itqlconfig    use an external configuration file\n");
-    usage.append("-l, --logconfig     use an external logging configuration " +
-        "file" + eol);
-    usage.append("-o, --postload      execute an iTQL script after " +
-        "interpreter stops," + eol);
-    usage.append("                    overriding default post-loading script" +
-        eol);
-    usage.append("-p, --preload       execute an iTQL script before " +
-        "interpreter starts," + eol);
-    usage.append("                    overriding default pre-loading script" +
-        eol);
-    usage.append("-s, --script        execute an iTQL script and quit" + eol);
-    usage.append(eol);
-    usage.append("The intepreter executes default pre- and post-loading " +
-        "scripts. These can be" + eol);
-    usage.append("used to load aliases etc. into the interpreter to simplify " +
-        "commands. The" + eol);
-    usage.append("default scripts are contained within the JAR file, " +
-        "however you can overide" + eol);
-    usage.append("these by placing files named default-pre.itql and " +
-        "default-post.itql in" + eol);
-    usage.append("the directory from which you run the interpreter, or by " +
-        "using the -p and" + eol);
-    usage.append("-o options." + eol);
-
-    // print the usage
-    System.out.println(usage.toString());
-  }
-
-  // printUsage()
-
-  /**
-   * 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();
-  }
-
-  // dumpConfig()
-
-  /**
-   * Loads an external iTQL 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 itqlConfURL the URL of the external iTQL interpreter configuration
-   *      file
-   * @return RETURNED VALUE TO DO
-   */
-  private boolean loadItqlConfig(URL itqlConfURL) {
-
-    // we don't support this feature yet
-    throw new UnsupportedOperationException();
-  }
-
-  // loadItqlConfig()
-
-  /**
-   * Executes a script.
-   *
-   * @param scriptURL the URL of the script to load
-   */
-  private void executeScript(URL scriptURL) {
-
-    // 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(),
-          "UTF-8"));
-
-      // execute the script!
-      String command = scriptIn.readLine();
-
-      while (command != null) {
-
-        // increment the line number
-        line++;
-
-        if (!command.equals("")) {
-
-          // execute the command
-          Answer answer = itqlBean.executeQuery(command);
-
-          // print the results
-          if (answer != null) {
-            answer.beforeFirst();
-
-            if (answer.isUnconstrained()) {
-              System.out.println("[ true ]");
-            } else {
-              while (answer.next()) {
-                System.out.print("[ ");
-                for (int index = 0; index < answer.getNumberOfVariables();
-                    index++) {
-                  System.out.print(String.valueOf(answer.getObject(index)));
-                  if (index < (answer.getNumberOfVariables() - 1)) {
-                    System.out.print(", ");
-                  }
-                }
-                System.out.println(" ]");
-              }
-            }
-          }
-
-          if (answer != null) {
-
-            answer.close();
-          }
-
-          String lastMessage = itqlBean.getLastMessage();
-          if ((lastMessage != null) && (lastMessage != "") && (ui != null)) {
-
-            System.out.println(lastMessage);
-          }
-
-        } // end if
-
-        // get the next command
-        command = scriptIn.readLine();
-
-      } // end if
-    } catch (ItqlInterpreterException pe) {
-
-      // let the user know the problem
-      System.err.println("Syntax error (line " + line + "): " +
-          pe.getMessage());
-      log.warn("Unable to execute script - " + scriptURL + " - " + pe);
-    } catch (TuplesException te) {
-
-      // let the user know the problem
-      System.err.println("Syntax error (line " + line + "): " +
-          te.getMessage());
-      log.warn("Unable to execute script - " + scriptURL + " - " + te);
-    } catch (IOException ioe) {
-
-      // let the user know the problem
-      System.err.println("Could not execute script - " + ioe);
-      log.warn("Unable to execute script - " + scriptURL + " - " + ioe);
-
-    } // try-catch
-
-  } // executeScript()
-
-  /**
-   * 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);
-  }
-
-  // loadLoggingConfig()
-
-  /**
-   * 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");
-      }
-
-      // try-catch
-    }
-
-    // end if
-  }
-
-  // getPostLoadingScriptURL()
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSession.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,980 @@
+/*
+ * 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;
+
+// Java 2 standard packages
+import java.io.*;
+import java.net.*;
+import java.util.*;
+
+import javax.xml.parsers.*;
+
+// Third party packages
+import org.apache.log4j.BasicConfigurator;
+import org.apache.log4j.Logger;
+import org.apache.log4j.xml.DOMConfigurator;
+
+// Automatically generated packages (SableCC)
+import org.mulgara.itql.analysis.DepthFirstAdapter;
+import org.mulgara.itql.lexer.Lexer;
+import org.mulgara.itql.lexer.LexerException;
+import org.mulgara.itql.node.*;
+import org.mulgara.itql.parser.Parser;
+import org.mulgara.itql.parser.ParserException;
+import org.mulgara.query.Answer;
+import org.mulgara.query.QueryException;
+import org.mulgara.query.TuplesException;
+
+import javax.swing.*;
+
+/**
+ * Interactive TQL session command line shell.
+ *
+ * @created 2001-Aug-17
+ *
+ * @author Simon Raboczi
+ * @author Tom Adams
+ * @author Andrew Newman
+ *
+ * @version $Revision: 1.8 $
+ *
+ * @modified $Date: 2005/01/05 04:58:15 $ by $Author: newmana $
+ *
+ * @maintenanceAuthor $Author: newmana $
+ *
+ * @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 ItqlSession {
+
+  /**
+   * Get line separator.
+   */
+  private static final String eol = System.getProperty("line.separator");
+
+  /**
+   * The prompt.
+   */
+  public final static String PROMPT = "iTQL> ";
+
+  /**
+   * The secondary prompt, indicating an incomplete command.
+   */
+  public final static String PROMPT2 = "      ";
+
+  //
+  // Constants
+  //
+
+  /**
+   * the log4j configuration file path (withing the JAR file)
+   */
+  private final static String LOG4J_CONFIG_PATH = "log4j-itql.xml";
+
+  /**
+   * the logging category to log to
+   */
+  private final static Logger log = Logger.getLogger(ItqlSession.class);
+
+  /**
+   * the default path to the pre-loading script
+   */
+  private final static String PRE_LOADING_SCRIPT_PATH = "default-pre.itql";
+
+  /**
+   * the default path to the post-loading script
+   */
+  private final static String POST_LOADING_SCRIPT_PATH = "default-post.itql";
+
+  //
+  // Private state
+  //
+
+  /**
+   * The graphical UI.
+   */
+  private static ItqlSessionUI ui;
+
+  /**
+   * The messages from the previous queries.
+   */
+  private List messages = new ArrayList();
+
+  /**
+   * The answers from the previous queries.
+   */
+  private List answers = new ArrayList();
+
+  /**
+   * The file name (URL) of the script to execute if -s is given.
+   */
+  private String script = null;
+
+  //
+  // Members
+  //
+
+  /**
+   * the iTQL interpreter associated with this session
+   */
+  private final ItqlInterpreterBean itqlBean;
+
+  /**
+   * the URL of the post-loading script
+   */
+  private URL postLoadingScriptURL = null;
+
+  /**
+   * the URL of the pre-loading script
+   */
+  private URL preLoadingScriptURL = null;
+
+  //
+  // Constructors
+  //
+
+  /**
+   * Creates a new ITQL session.
+   *
+   * @throws IOException if the logging configuration can't be read
+   * @throws QueryException if a connection can't be established
+   *   to the server
+   */
+  public ItqlSession() throws IOException, QueryException {
+
+    // load the default logging configuration
+    this.loadLoggingConfig();
+
+    itqlBean = new ItqlInterpreterBean();
+  }
+
+  /**
+   * 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
+   */
+  public static void session(ItqlSession session, InputStream in,
+      PrintStream out) {
+
+    // ui.print("@@build.label@@" + eol);
+
+    // display the copyright notice
+    ui.print("iTQL Command Line Interface" + eol +
+        "Copyright (C) 2001-2004 Tucana Technologies, Inc." + eol);
+
+    // print a help message
+    ui.print(eol + "Type \"help ;\", then enter for help." + eol + eol);
+
+    // print a prompt
+    ui.print(PROMPT);
+  }
+
+  /**
+   * Start an interactive TQL session.
+   *
+   * @param args command line parameters
+   * @throws IOException EXCEPTION TO DO
+   * @throws QueryException EXCEPTION TO DO
+   */
+  public static void main(String[] args) throws IOException, QueryException {
+
+    // create a new session to work with
+    ItqlSession itqlSession = new ItqlSession();
+
+    try {
+
+      // set the default pre- and post-loading scripts
+      itqlSession.retrieveDefaultLoadingScripts();
+
+      // create a parser to parse the command line options
+      ItqlOptionParser optsParser = new ItqlOptionParser(args);
+
+      // parse the
+      optsParser.parse();
+
+      // process the options
+      boolean startSession = itqlSession.processOptions(optsParser);
+
+      // log that we've processed the options
+      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
+      itqlSession.executeLoadingScript(itqlSession.getPreLoadingScriptURL());
+
+      if (itqlSession.getScript() != null) {
+
+        itqlSession.executeScript(new URL(itqlSession.getScript()));
+
+      } // end if
+
+      // log that we've executed the pre-loading script
+      if (log.isDebugEnabled()) {
+
+        log.debug("Executed pre-loading script");
+      }
+
+      // if we can, execute this session using std in and std out
+      if (startSession) {
+
+        // Create the UI.
+        JFrame app = new JFrame("iTQL Shell");
+        app.setSize(640, 480);
+        app.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+        ui = new ItqlSessionUI(itqlSession);
+        app.getContentPane().add(ui);
+
+        if (log.isInfoEnabled()) {
+
+          log.info("Starting iTQL interpreter");
+        }
+
+        ItqlSession.session(itqlSession, System.in, System.out);
+
+        // Make the UI visible
+        app.setVisible(true);
+
+        if (log.isInfoEnabled()) {
+
+          log.info("Stopping iTQL interpreter");
+        }
+
+        // log that we've executed the pre-loading script
+        if (log.isDebugEnabled()) {
+
+          log.debug("Executed post-loading script");
+        }
+      } else {
+
+        // execute the post-loading script
+        itqlSession.executeLoadingScript(itqlSession.getPostLoadingScriptURL());
+
+        // Close the session and exit.
+        itqlSession.close();
+        System.exit(0);
+      }
+    } catch (ItqlOptionParser.UnknownOptionException uoe) {
+
+      // log that the option we received was invalid
+      log.warn("Invalid command line option specified: " + uoe.getOptionName());
+
+      // let the user know about the invalid option
+      System.err.println("Invalid option: " + uoe.getOptionName());
+
+      // print the usage instructions
+      itqlSession.printUsage();
+    } catch (ItqlOptionParser.IllegalOptionValueException iove) {
+
+      // format the incorrect option string
+      String optionMsg =
+          "-" + iove.getOption().shortForm() + ", --" +
+          iove.getOption().longForm() + " = " + iove.getValue();
+
+      // log that the option value we received was invalid
+      log.warn("Invalid command line option value specified: " + optionMsg);
+
+      // let the user know about the invalid option
+      System.err.println("Invalid option value: " + optionMsg);
+
+      // print the usage instructions
+      itqlSession.printUsage();
+    }
+  }
+
+  // ItqlSession()
+  //
+  // Methods overriding the AbstractSession superclass
+  //
+
+  /**
+   * 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 the message from the execution of the last command.
+   */
+  public List getLastMessages() {
+
+    return messages;
+  }
+
+  /**
+   * Returns a list of Answers from the execution of the last command or series
+   * of commands.  Failures will have null answers in place.
+   */
+  public List getLastAnswers() {
+
+    return answers;
+  }
+
+  /**
+   * Returns the script to run.
+   *
+   * @return the script to run.
+   */
+  public String getScript() {
+
+    return script;
+  }
+
+  /**
+   * Executes a series of commands the given command.  Makes the result availabe
+   * via getLastMessages and getLastAnswers.
+   *
+   * @param command the command to execute
+   */
+  public void executeCommand(String command) {
+
+    // Reset answers and messages
+    answers.clear();
+    messages.clear();
+
+    String message = null;
+    Answer answer = null;
+    String[] queries = ItqlInterpreterBean.splitQuery(command);
+
+    for (int index = 0; index < queries.length; index++) {
+
+      try {
+
+        // log the command we're executing
+        if (log.isDebugEnabled()) {
+
+          log.debug("Starting execution of command \"" + command + "\"");
+        }
+
+        // execute the command
+        answer = itqlBean.executeQuery(queries[index]);
+
+        // close the session if requested
+        if (itqlBean.isQuitRequested()) {
+
+          close();
+        }
+
+        message = itqlBean.getLastMessage();
+
+        // log that we've executed the command
+        if (log.isDebugEnabled()) {
+
+          log.debug("Completed execution of commmand \"" + command + "\"");
+        }
+      } catch (UnsupportedOperationException uoe) {
+
+        // Known exception get the last message.
+        message = itqlBean.getLastMessage();
+        log.warn("Couldn't execute command", uoe);
+      } catch (ItqlInterpreterException iee) {
+
+        // Known exception get the last message.
+        message = itqlBean.getLastMessage();
+        log.warn("Couldn't execute command", iee);
+      } catch (Exception e) {
+
+        // Unknown exception get the exception's message.
+        message = e.getMessage();
+        log.error("Couldn't execute command", e);
+      } catch (Error e) {
+
+        // Unknown exception get the exception's message.
+        message = e.getMessage();
+        log.error("Couldn't execute command", e);
+      }
+
+      // Add the message and answer
+      messages.add(message);
+      answers.add(answer);
+    }
+  }
+
+  /**
+   * Sets the URL of the pre-loading script.
+   *
+   * @param preLoadingScriptURL the URL of the pre-loading script
+   */
+  private void setPreLoadingScriptURL(URL preLoadingScriptURL) {
+
+    this.preLoadingScriptURL = preLoadingScriptURL;
+  }
+
+  // getPreLoadingScriptURL()
+
+  /**
+   * Sets the URL of the post-loading script.
+   *
+   * @param postLoadingScriptURL the URL of the post-loading script
+   */
+  private void setPostLoadingScriptURL(URL postLoadingScriptURL) {
+
+    this.postLoadingScriptURL = postLoadingScriptURL;
+  }
+
+  // setInterpreter()
+
+  /**
+   * Returns the URL of the pre-loading script.
+   *
+   * @return the URL of the pre-loading script
+   */
+  private URL getPreLoadingScriptURL() {
+
+    return this.preLoadingScriptURL;
+  }
+
+  // setPostLoadingScriptURL()
+
+  /**
+   * Returns the URL of the post-loading script.
+   *
+   * @return the URL of the post-loading script
+   */
+  private URL getPostLoadingScriptURL() {
+
+    return this.postLoadingScriptURL;
+  }
+
+  // command()
+
+  /**
+   * Closes the session associated with this interpreter. Subclasses that
+   * override this method <strong>must</strong> call <code>super.close()</code>.
+   */
+  private void close() {
+
+    // Close the session, if any
+    itqlBean.setServerURI(null);
+    itqlBean.close();
+
+    // Exit program
+    System.exit(0);
+  }
+
+  // main()
+  //
+  // Internal methods
+  //
+
+  /**
+   * Retrieves the default loading scripts.
+   */
+  private void retrieveDefaultLoadingScripts() {
+
+    // locate the pre-loading script
+    URL preScriptURL = this.locateScript(PRE_LOADING_SCRIPT_PATH);
+
+    if (preScriptURL != null) {
+
+      this.setPreLoadingScriptURL(preScriptURL);
+    }
+
+    // locate the post-loading script
+    URL postScriptURL = this.locateScript(POST_LOADING_SCRIPT_PATH);
+
+    if (postScriptURL != null) {
+
+      this.setPostLoadingScriptURL(postScriptURL);
+    }
+  }
+
+  /**
+   * Locates the loading script with the given path. <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, null 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;
+    }
+
+    // end if
+    // log that we're looking for scripts
+    log.debug("Looking for script " + scriptPath + " in " + currentDirectory);
+
+    // try to find the script
+    File loadingScript = new File(currentDirectory + scriptPath);
+
+    if (loadingScript.exists() && loadingScript.isFile()) {
+
+      // log that we've found the file
+      log.debug("Found loading script - " + loadingScript);
+
+      // return the URL!!!
+      try {
+
+        scriptURL = loadingScript.toURL();
+      } catch (MalformedURLException mue) {
+
+        // log the error
+        log.warn("Unable to convert loading script filename to URL - " +
+            mue.getMessage());
+        System.err.println("Unable to convert loading script filename " +
+            "to URL - " + loadingScript);
+      }
+
+      // try-catch
+    } else {
+
+      // log that we're now looking in the classpath
+      log.debug("Looking for loading script " + scriptPath + " in classpath");
+
+      // try to obtain from the classpath
+      URL loadingScriptURL = ClassLoader.getSystemResource(scriptPath);
+
+      // set it
+      if (loadingScriptURL != null) {
+
+        log.debug("Found loading script at - " + loadingScriptURL);
+        scriptURL = loadingScriptURL;
+      }
+
+      // end if
+    }
+
+    // end if
+    // return the URL
+    return scriptURL;
+  }
+
+  // locateScript()
+
+  /**
+   * Executes the pre-loading script.
+   *
+   * @param loadingScriptURL the URL of the loading (pre/post) script to execute
+   */
+  private void executeLoadingScript(URL loadingScriptURL) {
+
+    // execute it
+    if (loadingScriptURL != null) {
+
+      // log that we're executing the script
+      log.debug("Executing loading script " + loadingScriptURL);
+
+      // execute the script
+      this.executeScript(loadingScriptURL);
+    }
+
+    // end if
+  }
+
+  // executeLoadingScript()
+
+  /**
+   * 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 RETURNED VALUE TO DO
+   */
+  private boolean processOptions(ItqlOptionParser parser) {
+
+    // log that we're processing command line options
+    log.debug("Processing command line options");
+
+    // flag to indicate whether we can start the interpreter
+    boolean startInterpreter = true;
+
+    try {
+
+      // find out if the user wants help
+      if (parser.getOptionValue(ItqlOptionParser.HELP) != null) {
+
+        // print the help
+        this.printUsage();
+
+        // don't start the interpreter
+        startInterpreter = false;
+      } else {
+
+        // dump the interpreter configuration
+        Object dumpConfig = parser.getOptionValue(ItqlOptionParser.DUMP_CONFIG);
+
+        if (dumpConfig != null) {
+
+          this.dumpConfig();
+        }
+
+        // end if
+        // load an external interpreter configuration file
+        Object itqlConf = parser.getOptionValue(ItqlOptionParser.ITQL_CONFIG);
+
+        if (itqlConf != null) {
+
+          this.loadItqlConfig(new URL( (String) itqlConf));
+        }
+
+        // end if
+        // load an external logging configuration file
+        Object logConf = parser.getOptionValue(ItqlOptionParser.LOG_CONFIG);
+
+        if (logConf != null) {
+
+          this.loadLoggingConfig(new URL( (String) logConf));
+        }
+
+        // end if
+        // find out whether to execute pre-and post loading scripts
+        Object defaultLoadingScripts =
+            parser.getOptionValue(ItqlOptionParser.NO_LOAD);
+
+        if (defaultLoadingScripts == null) {
+
+          // override the default pre-loading script
+          Object preScript = parser.getOptionValue(ItqlOptionParser.PRE_SCRIPT);
+
+          if (preScript != null) {
+
+            this.setPreLoadingScriptURL(new URL( (String) preScript));
+          }
+
+          // end if
+          // override the default post-loading script
+          Object postScript =
+              parser.getOptionValue(ItqlOptionParser.POST_SCRIPT);
+
+          if (postScript != null) {
+
+            this.setPostLoadingScriptURL(new URL( (String) preScript));
+          }
+
+          // end if
+        } else {
+
+          // log that we've turned off pre- and post-loading scripts
+          log.debug("Pre- and post-loading scripts disabled");
+
+          // unset default pre- and post-loading scripts
+          this.setPreLoadingScriptURL(null);
+          this.setPostLoadingScriptURL(null);
+        }
+
+        // execute an iTQL script and quit
+        script = (String) parser.getOptionValue(ItqlOptionParser.SCRIPT);
+
+        if (script != null) {
+
+          startInterpreter = false;
+
+        } // end if
+
+      } // end if
+    } catch (IOException ioe) {
+
+      // log the error
+      log.warn("Invalid URL on command line - " + ioe.getMessage());
+
+      // print the usage
+      System.err.println("Invalid URL - " + ioe.getMessage());
+      this.printUsage();
+
+      // don't start the interpreter
+      startInterpreter = false;
+    } catch (Exception e) {
+
+      // log the error
+      log.warn("Could not start interpreter - " + e.getMessage());
+
+      // let the user know
+      System.err.println("Error - " + e.getMessage());
+
+      // don't start the interpreter
+      startInterpreter = false;
+    }
+
+    // try-catch
+    // return the continue flag
+    return startInterpreter;
+  }
+
+  // processOptions()
+
+  /**
+   * Prints the usage instructions for the interpreter.
+   */
+  private void printUsage() {
+
+    // build the usage message
+    StringBuffer usage = new StringBuffer();
+    usage.append("Usage: java -jar <jarfile> ");
+
+    //usage.append("[-d|");
+    //usage.append("-g|");
+    //usage.append("-h] ");
+    usage.append("[-h|");
+    usage.append("-n] ");
+
+    //usage.append("[-i <url>] ");
+    usage.append("[-l <url>] ");
+    usage.append("[-o <url>] ");
+    usage.append("[-p <url>] ");
+    usage.append("[-s <url>]");
+    usage.append(eol);
+    usage.append(eol);
+
+    //usage.append("-d, --dumpconfig    dump the interpreter configuration to " +
+    //    "the current directory\n");
+    //usage.append("-g, --gui           display the iTQL GUI  ");
+    usage.append("-h, --help          display this help screen" + eol);
+    usage.append("-n, --noload        do not execute pre- and post-loading " +
+        "scripts (useful with -s)" + eol);
+
+    //usage.append("-i, --itqlconfig    use an external configuration file\n");
+    usage.append("-l, --logconfig     use an external logging configuration " +
+        "file" + eol);
+    usage.append("-o, --postload      execute an iTQL script after " +
+        "interpreter stops," + eol);
+    usage.append("                    overriding default post-loading script" +
+        eol);
+    usage.append("-p, --preload       execute an iTQL script before " +
+        "interpreter starts," + eol);
+    usage.append("                    overriding default pre-loading script" +
+        eol);
+    usage.append("-s, --script        execute an iTQL script and quit" + eol);
+    usage.append(eol);
+    usage.append("The intepreter executes default pre- and post-loading " +
+        "scripts. These can be" + eol);
+    usage.append("used to load aliases etc. into the interpreter to simplify " +
+        "commands. The" + eol);
+    usage.append("default scripts are contained within the JAR file, " +
+        "however you can overide" + eol);
+    usage.append("these by placing files named default-pre.itql and " +
+        "default-post.itql in" + eol);
+    usage.append("the directory from which you run the interpreter, or by " +
+        "using the -p and" + eol);
+    usage.append("-o options." + eol);
+
+    // print the usage
+    System.out.println(usage.toString());
+  }
+
+  // printUsage()
+
+  /**
+   * 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();
+  }
+
+  // dumpConfig()
+
+  /**
+   * Loads an external iTQL 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 itqlConfURL the URL of the external iTQL interpreter configuration
+   *      file
+   * @return RETURNED VALUE TO DO
+   */
+  private boolean loadItqlConfig(URL itqlConfURL) {
+
+    // we don't support this feature yet
+    throw new UnsupportedOperationException();
+  }
+
+  // loadItqlConfig()
+
+  /**
+   * Executes a script.
+   *
+   * @param scriptURL the URL of the script to load
+   */
+  private void executeScript(URL scriptURL) {
+
+    // 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(),
+          "UTF-8"));
+
+      // execute the script!
+      String command = scriptIn.readLine();
+
+      while (command != null) {
+
+        // increment the line number
+        line++;
+
+        if (!command.equals("")) {
+
+          // execute the command
+          Answer answer = itqlBean.executeQuery(command);
+
+          // print the results
+          if (answer != null) {
+            answer.beforeFirst();
+
+            if (answer.isUnconstrained()) {
+              System.out.println("[ true ]");
+            } else {
+              while (answer.next()) {
+                System.out.print("[ ");
+                for (int index = 0; index < answer.getNumberOfVariables();
+                    index++) {
+                  System.out.print(String.valueOf(answer.getObject(index)));
+                  if (index < (answer.getNumberOfVariables() - 1)) {
+                    System.out.print(", ");
+                  }
+                }
+                System.out.println(" ]");
+              }
+            }
+          }
+
+          if (answer != null) {
+
+            answer.close();
+          }
+
+          String lastMessage = itqlBean.getLastMessage();
+          if ((lastMessage != null) && (lastMessage != "") && (ui != null)) {
+
+            System.out.println(lastMessage);
+          }
+
+        } // end if
+
+        // get the next command
+        command = scriptIn.readLine();
+
+      } // end if
+    } catch (ItqlInterpreterException pe) {
+
+      // let the user know the problem
+      System.err.println("Syntax error (line " + line + "): " +
+          pe.getMessage());
+      log.warn("Unable to execute script - " + scriptURL + " - " + pe);
+    } catch (TuplesException te) {
+
+      // let the user know the problem
+      System.err.println("Syntax error (line " + line + "): " +
+          te.getMessage());
+      log.warn("Unable to execute script - " + scriptURL + " - " + te);
+    } catch (IOException ioe) {
+
+      // let the user know the problem
+      System.err.println("Could not execute script - " + ioe);
+      log.warn("Unable to execute script - " + scriptURL + " - " + ioe);
+
+    } // try-catch
+
+  } // executeScript()
+
+  /**
+   * 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);
+  }
+
+  // loadLoggingConfig()
+
+  /**
+   * 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");
+      }
+
+      // try-catch
+    }
+
+    // end if
+  }
+
+  // getPostLoadingScriptURL()
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,877 +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;
-
-/**
- * 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.beans.*;
-import java.io.*;
-import java.util.*;
-
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.*;
-import javax.swing.text.*;
-import javax.swing.event.*;
-
-import org.apache.log4j.*;
-import org.jrdf.graph.Node;
-
-import org.mulgara.query.Answer;
-import org.mulgara.query.TuplesException;
-
-public class ItqlSessionUI extends JScrollPane implements Runnable,
-    KeyListener, java.awt.event.MouseListener, ActionListener {
-
-  /**
-   * The logging category to log to
-   */
-  private final static Logger log = Logger.getLogger(ItqlSessionUI.class);
-
-  /**
-   * Inputstream to take user input.
-   */
-  private InputStream in;
-
-  /**
-   * Outputstream to display user output.
-   */
-   private PrintStream out;
-
-  /**
-   * Used to pipe input.
-   */
-  private InputStream inPipe;
-
-  /**
-   * Used to pipe output.
-   */
-  private OutputStream outPipe;
-
-  /**
-   * The iTQL session to send queries and used to send results.
-   */
-  private ItqlSession itqlSession;
-
-  /**
-   * The list of history items.
-   */
-  private ArrayList history = new ArrayList();
-
-  /**
-   * 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 ItqlSessionUI(ItqlSession newItqlSession) {
-
-    super();
-
-    itqlSession = newItqlSession;
-    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);
-
-    outPipe = new PipedOutputStream();
-    try {
-
-      in = new PipedInputStream((PipedOutputStream) outPipe);
-    } catch (IOException e) {
-
-      log.error("Error creating input stream", e);
-    }
-
-    PipedOutputStream pout = new PipedOutputStream();
-    out = new PrintStream(pout);
-    try {
-
-      inPipe = new PipedInputStream(pout);
-    } catch (IOException e) {
-
-      log.error("Error creating input pipe", e);
-    }
-
-    // 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 + System.getProperty("line.separator");
-
-      // 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() {
-
-    println();
-    print(ItqlSession.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 + System.getProperty("line.separator"));
-    text.repaint();
-  }
-
-  /**
-   * Prints empty line.
-   */
-  public void println() {
-
-    print(System.getProperty("line.separator"));
-    text.repaint();
-  }
-
-  /**
-   * Prints a message to the UI.
-   *
-   * @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);
-      }
-    });
-  }
-
-  /**
-   * 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.
-   *
-   * @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);
-        }
-      }
-    });
-  }
-
-  /**
-   * 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) {
-
-      if (font.isBold()) {
-
-        StyleConstants.setBold(attr, true);
-      } else {
-
-        StyleConstants.setBold(attr, false);
-      }
-
-      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 runs while waiting for input.
-   */
-  public void run() {
-
-    try {
-
-      byte[] buffer = new byte[255];
-      int read;
-      while ((read = inPipe.read(buffer)) != -1) {
-
-        print(new String(buffer, 0, read));
-      }
-    } catch (IOException e) {
-
-      log.error("Error reading input", e);
-    }
-  }
-
-  /**
-   * If not in the event thread run via SwingUtilities.invokeAndWait()
-   */
-  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 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() {
-
-      itqlSession.executeCommand(command);
-      println();
-
-      java.util.List answers = itqlSession.getLastAnswers();
-      java.util.List messages = itqlSession.getLastMessages();
-
-      int answerIndex = 0;
-      String lastMessage;
-
-      while (answerIndex < answers.size()) {
-
-        lastMessage = (String) messages.get(answerIndex);
-
-        try {
-
-          // Assume the same number of answers and messages
-          Answer 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.
-            print("Executing Query " + (answerIndex+1),
-                new Font("Monospaced", Font.BOLD, 12), Color.BLACK);
-            println();
-          }
-
-          // print the results
-          if (answer != null) {
-
-            boolean hasAnswers = true;
-
-            answer.beforeFirst();
-            long rowCount = 0;
-
-            if (answer.isUnconstrained()) {
-              println("[ true ]");
-              rowCount = 1;
-            } else {
-              if (!answer.next()) {
-                print("No results returned.",
-                    new Font("Monospaced", Font.BOLD, 12), 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) {
-              print(rowCount + " rows returned.",
-                  new Font("Monospaced", Font.BOLD, 12), 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, new Font("Monospaced", Font.BOLD, 12),
-              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: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlSessionUI.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,877 @@
+/*
+ * 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.beans.*;
+import java.io.*;
+import java.util.*;
+
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+import javax.swing.text.*;
+import javax.swing.event.*;
+
+import org.apache.log4j.*;
+import org.jrdf.graph.Node;
+
+import org.mulgara.query.Answer;
+import org.mulgara.query.TuplesException;
+
+public class ItqlSessionUI extends JScrollPane implements Runnable,
+    KeyListener, java.awt.event.MouseListener, ActionListener {
+
+  /**
+   * The logging category to log to
+   */
+  private final static Logger log = Logger.getLogger(ItqlSessionUI.class);
+
+  /**
+   * Inputstream to take user input.
+   */
+  private InputStream in;
+
+  /**
+   * Outputstream to display user output.
+   */
+   private PrintStream out;
+
+  /**
+   * Used to pipe input.
+   */
+  private InputStream inPipe;
+
+  /**
+   * Used to pipe output.
+   */
+  private OutputStream outPipe;
+
+  /**
+   * The iTQL session to send queries and used to send results.
+   */
+  private ItqlSession itqlSession;
+
+  /**
+   * The list of history items.
+   */
+  private ArrayList history = new ArrayList();
+
+  /**
+   * 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 ItqlSessionUI(ItqlSession newItqlSession) {
+
+    super();
+
+    itqlSession = newItqlSession;
+    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);
+
+    outPipe = new PipedOutputStream();
+    try {
+
+      in = new PipedInputStream((PipedOutputStream) outPipe);
+    } catch (IOException e) {
+
+      log.error("Error creating input stream", e);
+    }
+
+    PipedOutputStream pout = new PipedOutputStream();
+    out = new PrintStream(pout);
+    try {
+
+      inPipe = new PipedInputStream(pout);
+    } catch (IOException e) {
+
+      log.error("Error creating input pipe", e);
+    }
+
+    // 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 + System.getProperty("line.separator");
+
+      // 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() {
+
+    println();
+    print(ItqlSession.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 + System.getProperty("line.separator"));
+    text.repaint();
+  }
+
+  /**
+   * Prints empty line.
+   */
+  public void println() {
+
+    print(System.getProperty("line.separator"));
+    text.repaint();
+  }
+
+  /**
+   * Prints a message to the UI.
+   *
+   * @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);
+      }
+    });
+  }
+
+  /**
+   * 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.
+   *
+   * @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);
+        }
+      }
+    });
+  }
+
+  /**
+   * 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) {
+
+      if (font.isBold()) {
+
+        StyleConstants.setBold(attr, true);
+      } else {
+
+        StyleConstants.setBold(attr, false);
+      }
+
+      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 runs while waiting for input.
+   */
+  public void run() {
+
+    try {
+
+      byte[] buffer = new byte[255];
+      int read;
+      while ((read = inPipe.read(buffer)) != -1) {
+
+        print(new String(buffer, 0, read));
+      }
+    } catch (IOException e) {
+
+      log.error("Error reading input", e);
+    }
+  }
+
+  /**
+   * If not in the event thread run via SwingUtilities.invokeAndWait()
+   */
+  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 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() {
+
+      itqlSession.executeCommand(command);
+      println();
+
+      java.util.List answers = itqlSession.getLastAnswers();
+      java.util.List messages = itqlSession.getLastMessages();
+
+      int answerIndex = 0;
+      String lastMessage;
+
+      while (answerIndex < answers.size()) {
+
+        lastMessage = (String) messages.get(answerIndex);
+
+        try {
+
+          // Assume the same number of answers and messages
+          Answer 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.
+            print("Executing Query " + (answerIndex+1),
+                new Font("Monospaced", Font.BOLD, 12), Color.BLACK);
+            println();
+          }
+
+          // print the results
+          if (answer != null) {
+
+            boolean hasAnswers = true;
+
+            answer.beforeFirst();
+            long rowCount = 0;
+
+            if (answer.isUnconstrained()) {
+              println("[ true ]");
+              rowCount = 1;
+            } else {
+              if (!answer.next()) {
+                print("No results returned.",
+                    new Font("Monospaced", Font.BOLD, 12), 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) {
+              print(rowCount + " rows returned.",
+                  new Font("Monospaced", Font.BOLD, 12), 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, new Font("Monospaced", Font.BOLD, 12),
+              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();
+    }
+  };
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,71 +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.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;
-  }
-
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ItqlUtil.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -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;
+  }
+
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/Login.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/Login.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/Login.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,67 +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;
-
-
-/**
- * Record for the storage of credentials. These are accumulated within the
- * {@link org.mulgara.server.Session} and forwarded on to the appropriate
- * databases.
- *
- * @created 2001-Dec-18
- * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
- * @version $Revision: 1.8 $
- * @modified $Date: 2005/01/05 04:58:15 $ by $Author: newmana $
- * @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>
- */
-class Login {
-
-  /**
-   * Identity.
-   */
-  final String username;
-
-  /**
-   * Authentication data.
-   */
-  final char[] password;
-
-  /**
-   * Construct a record.
-   *
-   * @param username PARAMETER TO DO
-   * @param password PARAMETER TO DO
-   */
-  Login(String username, char[] password) {
-
-    this.username = username;
-    this.password = password;
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/Login.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/Login.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/Login.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/Login.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,67 @@
+/*
+ * 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;
+
+
+/**
+ * Record for the storage of credentials. These are accumulated within the
+ * {@link org.mulgara.server.Session} and forwarded on to the appropriate
+ * databases.
+ *
+ * @created 2001-Dec-18
+ * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
+ * @version $Revision: 1.8 $
+ * @modified $Date: 2005/01/05 04:58:15 $ by $Author: newmana $
+ * @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>
+ */
+class Login {
+
+  /**
+   * Identity.
+   */
+  final String username;
+
+  /**
+   * Authentication data.
+   */
+  final char[] password;
+
+  /**
+   * Construct a record.
+   *
+   * @param username PARAMETER TO DO
+   * @param password PARAMETER TO DO
+   */
+  Login(String username, char[] password) {
+
+    this.username = username;
+    this.password = password;
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,550 +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;
-
-// Java 2 standard packages
-import java.net.*;
-import java.util.*;
-
-// Third party packages
-import org.apache.log4j.Logger;
-
-// Automatically generated packages (SableCC)
-import org.mulgara.itql.node.AAndModelTerm;
-import org.mulgara.itql.node.AExpressionModelFactor;
-import org.mulgara.itql.node.AFactorModelPart;
-import org.mulgara.itql.node.AOrModelExpression;
-import org.mulgara.itql.node.APartModelTerm;
-import org.mulgara.itql.node.AResourceModelFactor;
-import org.mulgara.itql.node.ATermModelExpression;
-import org.mulgara.itql.node.AXorModelPart;
-import org.mulgara.itql.node.PModelExpression;
-import org.mulgara.itql.node.PModelFactor;
-import org.mulgara.itql.node.PModelPart;
-import org.mulgara.itql.node.PModelTerm;
-import org.mulgara.query.ModelExpression;
-import org.mulgara.query.ModelIntersection;
-import org.mulgara.query.ModelPartition;
-import org.mulgara.query.ModelResource;
-import org.mulgara.query.ModelUnion;
-import org.mulgara.query.QueryException;
-import org.mulgara.util.ServerURIHandler;
-
-/**
- * Builds model expressions using input from the iTQL command interpreter.
- *
- * @created 2001-09-11
- *
- * @author Tom Adams
- *
- * @version $Revision: 1.9 $
- *
- * @modified $Date: 2005/04/04 11:30:11 $ by $Author: tomadams $
- *
- * @maintenanceAuthor $Author: tomadams $
- *
- * @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 ModelExpressionBuilder {
-
-  //
-  // Constants
-  //
-
-  /**
-   * the category to log to
-   */
-  private final static Logger logger =
-    Logger.getLogger(ModelExpressionBuilder.class.getName());
-
-  //
-  // Public API (methods overridden from ExpressionBuilder)
-  //
-
-  /**
-   * Builds a {@link org.mulgara.query.ModelExpression} object from a {@link
-   * 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
-   * @throws QueryException if <code>rawModelExpression</code> does not
-   *      represent a valid query
-   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
-   *      a resource whose text violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
-   */
-  public static ModelExpression build(Map<String,URI> aliasMap,
-    PModelExpression expression) throws QueryException, URISyntaxException {
-
-    // validate aliasMap parameter
-    if (aliasMap == null) {
-
-      throw new IllegalArgumentException("Null \"aliasMap\" parameter");
-    }
-
-    // end if
-    // validate expression parameter
-    if (expression == null) {
-
-      throw new IllegalArgumentException("Null \"expression\" parameter");
-    }
-
-    // end if
-    // logger that we're building a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building model expression from " + expression);
-    }
-
-    // build the model expression from the parser input
-    ModelExpression modelExpression = buildModelExpression(expression, aliasMap);
-
-    // logger that we've building successfully built a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Successfully built model expression from " + expression);
-    }
-
-    // return the model expression
-    return modelExpression;
-  }
-
-  // build()
-  //
-  // Internal methods
-  //
-
-  /**
-   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
-   * {@link org.mulgara.itql.node.PModelExpression}.
-   *
-   * @param rawModelExpression a raw model expression from the parser
-   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
-   *      creating a {@link org.mulgara.query.Query}
-   * @throws QueryException if <code>rawModelExpression</code> does not
-   *      represent a valid query
-   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
-   *      a resource whose text violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
-   */
-  private static ModelExpression buildModelExpression(
-    PModelExpression rawModelExpression, Map<String,URI> aliasMap)
-    throws QueryException, URISyntaxException {
-
-    // validate the rawModelExpression parameter
-    if (rawModelExpression == null) {
-
-      throw new IllegalArgumentException("Null \"rawModelExpression\" " +
-        "parameter");
-    }
-
-    // end if
-    // logger that we're building a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building model expression from " + rawModelExpression);
-    }
-
-    // create a new model expression that we can return
-    ModelExpression modelExpression = null;
-
-    // drill down to find its constituents
-    if (rawModelExpression instanceof AOrModelExpression) {
-
-      // logger that we've found a OR model expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found OR model expression " + rawModelExpression);
-      }
-
-      // get the OR model expression
-      PModelExpression orModelExpression =
-        ((AOrModelExpression) rawModelExpression).getModelExpression();
-
-      // get the model term
-      PModelTerm modelTerm =
-        ((AOrModelExpression) rawModelExpression).getModelTerm();
-
-      // logger that we've found the operands of the union
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with model expression " + orModelExpression +
-            " & model term " + modelTerm);
-      }
-
-      // get the LHS and RHS operands of the union
-      ModelExpression lhs = buildModelExpression(orModelExpression, aliasMap);
-      ModelExpression rhs = buildModelExpression(modelTerm, aliasMap);
-
-      // logger that we've resolved the operands
-      if (logger.isDebugEnabled()) {
-        logger.debug("Resolved LHS union operand " + lhs);
-        logger.debug("Resolved RHS union operand " + rhs);
-      }
-
-      // apply the union
-      modelExpression = new ModelUnion(lhs, rhs);
-    } else if (rawModelExpression instanceof ATermModelExpression) {
-
-      // logger that we've got a term model expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found term model expression " + rawModelExpression);
-      }
-
-      // get the model term
-      PModelTerm modelTerm = ((ATermModelExpression)rawModelExpression).getModelTerm();
-
-      // logger that we're about to resolve the term into an expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with model term " + modelTerm);
-      }
-
-      // drill down into the model term
-      modelExpression = buildModelExpression(modelTerm, aliasMap);
-    }
-
-    // end if
-    // we should not be returning null
-    if (modelExpression == null) {
-
-      throw new QueryException("Unable to parse ITQL model expression " +
-        "into a valid model expression");
-    }
-
-    // end if
-    // logger that we've created a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Created model expression " + modelExpression);
-    }
-
-    // return the built up expression
-    return modelExpression;
-  }
-
-  // buildModelExpression()
-
-  /**
-   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
-   * {@link org.mulgara.itql.node.PModelTerm}.
-   *
-   * @param rawModelTerm a raw model term from the parser
-   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
-   *      creating a {@link org.mulgara.query.Query}
-   * @throws QueryException if <code>rawModelExpression</code> does not
-   *      represent a valid query
-   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
-   *      a resource whose text violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
-   */
-  private static ModelExpression buildModelExpression(
-      PModelTerm rawModelTerm, Map<String,URI> aliasMap
-    ) throws QueryException, URISyntaxException {
-
-    // validate the rawModelTerm parameter
-    if (rawModelTerm == null) {
-
-      throw new IllegalArgumentException("Null \"rawModelTerm\" " +
-        "parameter");
-    }
-
-    // end if
-    // logger that we're building a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building model expression from " + rawModelTerm);
-    }
-
-    // create a new model expression that we can return
-    ModelExpression modelExpression = null;
-
-    // drill down into the model term
-    if (rawModelTerm instanceof APartModelTerm) {
-
-      // logger that we've got a factor model term
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found factor contraint term " + rawModelTerm);
-      }
-
-      // get the model factor
-      PModelPart modelPart = ((APartModelTerm) rawModelTerm).getModelPart();
-
-      // logger that we're recursing with a model part
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with model part " + modelPart);
-      }
-
-      // drill down into the model part
-      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();
-
-      // get the model part
-      PModelPart modelPart = ((AAndModelTerm)rawModelTerm).getModelPart();
-
-      // logger that we've found the operands of the union
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with model term " + modelTerm +
-            " & model part " + modelPart);
-      }
-
-      // get the LHS and RHS operands of the intersection
-      ModelExpression lhs = buildModelExpression(modelTerm, aliasMap);
-      ModelExpression rhs = buildModelExpression(modelPart, aliasMap);
-
-      // logger that we've resolved the operands
-      if (logger.isDebugEnabled()) {
-        logger.debug("Resolved LHS intersection operand " + lhs);
-        logger.debug("Resolved RHS intersection operand " + rhs);
-      }
-
-      // apply the intersection
-      modelExpression = new ModelIntersection(lhs, rhs);
-    }
-
-    // end if
-    // we should not be returning null
-    if (modelExpression == null) {
-
-      throw new QueryException("Unable to parse ITQL model term into a valid model expression");
-    }
-
-    // end if
-    // logger that we've created a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Created model expression " + modelExpression);
-    }
-
-    // return the built up expression
-    return modelExpression;
-  }
-
-  // buildModelExpression()
-
-  /**
-   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
-   * {@link org.mulgara.itql.node.PModelPart}.
-   *
-   * @param rawModelPart a raw model part from the parser
-   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
-   *      creating a {@link org.mulgara.query.Query}
-   * @throws QueryException if <code>rawModelExpression</code> does not
-   *      represent a valid query
-   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
-   *      a resource whose text violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
-   */
-  private static ModelExpression buildModelExpression(
-      PModelPart rawModelPart, Map<String,URI> aliasMap
-    ) throws QueryException, URISyntaxException {
-
-    // validate the rawModelPart parameter
-    if (rawModelPart == null) {
-      throw new IllegalArgumentException("Null \"rawModelPart\" " +
-        "parameter");
-    }
-
-    // end if
-    // logger that we're building a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building model expression from " + rawModelPart);
-    }
-
-    // create a new model expression that we can return
-    ModelExpression modelExpression = null;
-
-    // drill down into the model term
-    if (rawModelPart instanceof AFactorModelPart) {
-
-      // logger that we've got a factor model term
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found factor contraint term " + rawModelPart);
-      }
-
-      // get the model factor
-      PModelFactor modelFactor = ((AFactorModelPart)rawModelPart).getModelFactor();
-
-      // logger that we're recursing with a model factor
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with model factor " + modelFactor);
-      }
-
-      // drill down into the model part
-      modelExpression = buildModelExpression(modelFactor, aliasMap);
-    } else if (rawModelPart instanceof AXorModelPart) {
-
-      // logger that we've got a AND model term
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found AND contraint term " + rawModelPart);
-      }
-
-      // get the model term
-      PModelPart modelPart = ((AXorModelPart)rawModelPart).getModelPart();
-
-      // get the model factor
-      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);
-      }
-
-      // get the LHS and RHS operands of the intersection
-      ModelExpression lhs = buildModelExpression(modelPart, aliasMap);
-      ModelExpression rhs = buildModelExpression(modelFactor, aliasMap);
-
-      // logger that we've resolved the operands
-      if (logger.isDebugEnabled()) {
-        logger.debug("Resolved LHS intersection operand " + lhs);
-        logger.debug("Resolved RHS intersection operand " + rhs);
-      }
-
-      // apply the intersection
-      modelExpression = new ModelPartition(lhs, rhs);
-    }
-
-    // end if
-    // we should not be returning null
-    if (modelExpression == null) {
-
-      throw new QueryException("Unable to parse ITQL model term into a valid model expression");
-    }
-
-    // end if
-    // logger that we've created a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Created model expression " + modelExpression);
-    }
-
-    // return the built up expression
-    return modelExpression;
-  }
-
-  // buildModelExpression()
-
-  /**
-   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
-   * {@link org.mulgara.itql.node.PModelFactor}.
-   *
-   * @param rawModelFactor a raw model factor from the parser
-   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
-   *      creating a {@link org.mulgara.query.Query}
-   * @throws QueryException if <code>rawModelExpression</code> does not
-   *      represent a valid query
-   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
-   *      a resource whose text violates <a
-   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
-   */
-  private static ModelExpression buildModelExpression(
-        PModelFactor rawModelFactor, Map<String,URI> aliasMap
-      ) throws QueryException, URISyntaxException {
-
-    // validate the rawModelFactor parameter
-    if (rawModelFactor == null) {
-
-      throw new IllegalArgumentException("Null \"rawModelFactor\" parameter");
-    }
-
-    // end if
-    // logger that we're building a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Building model expression from " + rawModelFactor);
-    }
-
-    // create a new model expression that we can return
-    ModelExpression modelExpression = null;
-
-    // drill down into the model term
-    if (rawModelFactor instanceof AResourceModelFactor) {
-
-      // logger that we've got a model model factor
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found resource model factor " + rawModelFactor);
-      }
-
-      // get the resource
-      String resource = ((AResourceModelFactor)rawModelFactor).getResource().getText();
-
-      // logger that we've found a resource
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found resource " + resource);
-      }
-
-      // this resource is what we're looking for
-      URI modelURI = URIUtil.convertToURI(resource, aliasMap);
-      modelExpression = new ModelResource(ServerURIHandler.removePort(modelURI));
-    } else if (rawModelFactor instanceof AExpressionModelFactor) {
-
-      // logger that we've got an expression model factor
-      if (logger.isDebugEnabled()) {
-        logger.debug("Found factor expression model factor " + rawModelFactor);
-      }
-
-      // get the model expression
-      PModelExpression embeddedModelExpression = ((AExpressionModelFactor)rawModelFactor).getModelExpression();
-
-      // logger that we're recursing with a model expression
-      if (logger.isDebugEnabled()) {
-        logger.debug("Recursing with model factor " + modelExpression);
-      }
-
-      // build the model expression
-      modelExpression = buildModelExpression(embeddedModelExpression, aliasMap);
-    }
-
-    // end if
-    // we should not be returning null
-    if (modelExpression == null) {
-
-      throw new QueryException("Unable to parse ITQL model factor " +
-        "into a valid model expression");
-    }
-
-    // end if
-    // logger that we've created a model expression
-    if (logger.isDebugEnabled()) {
-      logger.debug("Created model expression " + modelExpression);
-    }
-
-    // return the built up expression
-    return modelExpression;
-  }
-
-  // buildModelExpression()
-}
-
-
-// ModelExpressionBuilder

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ModelExpressionBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,550 @@
+/*
+ * 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;
+
+// Java 2 standard packages
+import java.net.*;
+import java.util.*;
+
+// Third party packages
+import org.apache.log4j.Logger;
+
+// Automatically generated packages (SableCC)
+import org.mulgara.itql.node.AAndModelTerm;
+import org.mulgara.itql.node.AExpressionModelFactor;
+import org.mulgara.itql.node.AFactorModelPart;
+import org.mulgara.itql.node.AOrModelExpression;
+import org.mulgara.itql.node.APartModelTerm;
+import org.mulgara.itql.node.AResourceModelFactor;
+import org.mulgara.itql.node.ATermModelExpression;
+import org.mulgara.itql.node.AXorModelPart;
+import org.mulgara.itql.node.PModelExpression;
+import org.mulgara.itql.node.PModelFactor;
+import org.mulgara.itql.node.PModelPart;
+import org.mulgara.itql.node.PModelTerm;
+import org.mulgara.query.ModelExpression;
+import org.mulgara.query.ModelIntersection;
+import org.mulgara.query.ModelPartition;
+import org.mulgara.query.ModelResource;
+import org.mulgara.query.ModelUnion;
+import org.mulgara.query.QueryException;
+import org.mulgara.util.ServerURIHandler;
+
+/**
+ * Builds model expressions using input from the iTQL command interpreter.
+ *
+ * @created 2001-09-11
+ *
+ * @author Tom Adams
+ *
+ * @version $Revision: 1.9 $
+ *
+ * @modified $Date: 2005/04/04 11:30:11 $ by $Author: tomadams $
+ *
+ * @maintenanceAuthor $Author: tomadams $
+ *
+ * @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 ModelExpressionBuilder {
+
+  //
+  // Constants
+  //
+
+  /**
+   * the category to log to
+   */
+  private final static Logger logger =
+    Logger.getLogger(ModelExpressionBuilder.class.getName());
+
+  //
+  // Public API (methods overridden from ExpressionBuilder)
+  //
+
+  /**
+   * Builds a {@link org.mulgara.query.ModelExpression} object from a {@link
+   * 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
+   * @throws QueryException if <code>rawModelExpression</code> does not
+   *      represent a valid query
+   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
+   *      a resource whose text violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
+   */
+  public static ModelExpression build(Map<String,URI> aliasMap,
+    PModelExpression expression) throws QueryException, URISyntaxException {
+
+    // validate aliasMap parameter
+    if (aliasMap == null) {
+
+      throw new IllegalArgumentException("Null \"aliasMap\" parameter");
+    }
+
+    // end if
+    // validate expression parameter
+    if (expression == null) {
+
+      throw new IllegalArgumentException("Null \"expression\" parameter");
+    }
+
+    // end if
+    // logger that we're building a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Building model expression from " + expression);
+    }
+
+    // build the model expression from the parser input
+    ModelExpression modelExpression = buildModelExpression(expression, aliasMap);
+
+    // logger that we've building successfully built a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Successfully built model expression from " + expression);
+    }
+
+    // return the model expression
+    return modelExpression;
+  }
+
+  // build()
+  //
+  // Internal methods
+  //
+
+  /**
+   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
+   * {@link org.mulgara.itql.node.PModelExpression}.
+   *
+   * @param rawModelExpression a raw model expression from the parser
+   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
+   *      creating a {@link org.mulgara.query.Query}
+   * @throws QueryException if <code>rawModelExpression</code> does not
+   *      represent a valid query
+   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
+   *      a resource whose text violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
+   */
+  private static ModelExpression buildModelExpression(
+    PModelExpression rawModelExpression, Map<String,URI> aliasMap)
+    throws QueryException, URISyntaxException {
+
+    // validate the rawModelExpression parameter
+    if (rawModelExpression == null) {
+
+      throw new IllegalArgumentException("Null \"rawModelExpression\" " +
+        "parameter");
+    }
+
+    // end if
+    // logger that we're building a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Building model expression from " + rawModelExpression);
+    }
+
+    // create a new model expression that we can return
+    ModelExpression modelExpression = null;
+
+    // drill down to find its constituents
+    if (rawModelExpression instanceof AOrModelExpression) {
+
+      // logger that we've found a OR model expression
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found OR model expression " + rawModelExpression);
+      }
+
+      // get the OR model expression
+      PModelExpression orModelExpression =
+        ((AOrModelExpression) rawModelExpression).getModelExpression();
+
+      // get the model term
+      PModelTerm modelTerm =
+        ((AOrModelExpression) rawModelExpression).getModelTerm();
+
+      // logger that we've found the operands of the union
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with model expression " + orModelExpression +
+            " & model term " + modelTerm);
+      }
+
+      // get the LHS and RHS operands of the union
+      ModelExpression lhs = buildModelExpression(orModelExpression, aliasMap);
+      ModelExpression rhs = buildModelExpression(modelTerm, aliasMap);
+
+      // logger that we've resolved the operands
+      if (logger.isDebugEnabled()) {
+        logger.debug("Resolved LHS union operand " + lhs);
+        logger.debug("Resolved RHS union operand " + rhs);
+      }
+
+      // apply the union
+      modelExpression = new ModelUnion(lhs, rhs);
+    } else if (rawModelExpression instanceof ATermModelExpression) {
+
+      // logger that we've got a term model expression
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found term model expression " + rawModelExpression);
+      }
+
+      // get the model term
+      PModelTerm modelTerm = ((ATermModelExpression)rawModelExpression).getModelTerm();
+
+      // logger that we're about to resolve the term into an expression
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with model term " + modelTerm);
+      }
+
+      // drill down into the model term
+      modelExpression = buildModelExpression(modelTerm, aliasMap);
+    }
+
+    // end if
+    // we should not be returning null
+    if (modelExpression == null) {
+
+      throw new QueryException("Unable to parse ITQL model expression " +
+        "into a valid model expression");
+    }
+
+    // end if
+    // logger that we've created a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Created model expression " + modelExpression);
+    }
+
+    // return the built up expression
+    return modelExpression;
+  }
+
+  // buildModelExpression()
+
+  /**
+   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
+   * {@link org.mulgara.itql.node.PModelTerm}.
+   *
+   * @param rawModelTerm a raw model term from the parser
+   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
+   *      creating a {@link org.mulgara.query.Query}
+   * @throws QueryException if <code>rawModelExpression</code> does not
+   *      represent a valid query
+   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
+   *      a resource whose text violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
+   */
+  private static ModelExpression buildModelExpression(
+      PModelTerm rawModelTerm, Map<String,URI> aliasMap
+    ) throws QueryException, URISyntaxException {
+
+    // validate the rawModelTerm parameter
+    if (rawModelTerm == null) {
+
+      throw new IllegalArgumentException("Null \"rawModelTerm\" " +
+        "parameter");
+    }
+
+    // end if
+    // logger that we're building a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Building model expression from " + rawModelTerm);
+    }
+
+    // create a new model expression that we can return
+    ModelExpression modelExpression = null;
+
+    // drill down into the model term
+    if (rawModelTerm instanceof APartModelTerm) {
+
+      // logger that we've got a factor model term
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found factor contraint term " + rawModelTerm);
+      }
+
+      // get the model factor
+      PModelPart modelPart = ((APartModelTerm) rawModelTerm).getModelPart();
+
+      // logger that we're recursing with a model part
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with model part " + modelPart);
+      }
+
+      // drill down into the model part
+      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();
+
+      // get the model part
+      PModelPart modelPart = ((AAndModelTerm)rawModelTerm).getModelPart();
+
+      // logger that we've found the operands of the union
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with model term " + modelTerm +
+            " & model part " + modelPart);
+      }
+
+      // get the LHS and RHS operands of the intersection
+      ModelExpression lhs = buildModelExpression(modelTerm, aliasMap);
+      ModelExpression rhs = buildModelExpression(modelPart, aliasMap);
+
+      // logger that we've resolved the operands
+      if (logger.isDebugEnabled()) {
+        logger.debug("Resolved LHS intersection operand " + lhs);
+        logger.debug("Resolved RHS intersection operand " + rhs);
+      }
+
+      // apply the intersection
+      modelExpression = new ModelIntersection(lhs, rhs);
+    }
+
+    // end if
+    // we should not be returning null
+    if (modelExpression == null) {
+
+      throw new QueryException("Unable to parse ITQL model term into a valid model expression");
+    }
+
+    // end if
+    // logger that we've created a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Created model expression " + modelExpression);
+    }
+
+    // return the built up expression
+    return modelExpression;
+  }
+
+  // buildModelExpression()
+
+  /**
+   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
+   * {@link org.mulgara.itql.node.PModelPart}.
+   *
+   * @param rawModelPart a raw model part from the parser
+   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
+   *      creating a {@link org.mulgara.query.Query}
+   * @throws QueryException if <code>rawModelExpression</code> does not
+   *      represent a valid query
+   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
+   *      a resource whose text violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
+   */
+  private static ModelExpression buildModelExpression(
+      PModelPart rawModelPart, Map<String,URI> aliasMap
+    ) throws QueryException, URISyntaxException {
+
+    // validate the rawModelPart parameter
+    if (rawModelPart == null) {
+      throw new IllegalArgumentException("Null \"rawModelPart\" " +
+        "parameter");
+    }
+
+    // end if
+    // logger that we're building a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Building model expression from " + rawModelPart);
+    }
+
+    // create a new model expression that we can return
+    ModelExpression modelExpression = null;
+
+    // drill down into the model term
+    if (rawModelPart instanceof AFactorModelPart) {
+
+      // logger that we've got a factor model term
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found factor contraint term " + rawModelPart);
+      }
+
+      // get the model factor
+      PModelFactor modelFactor = ((AFactorModelPart)rawModelPart).getModelFactor();
+
+      // logger that we're recursing with a model factor
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with model factor " + modelFactor);
+      }
+
+      // drill down into the model part
+      modelExpression = buildModelExpression(modelFactor, aliasMap);
+    } else if (rawModelPart instanceof AXorModelPart) {
+
+      // logger that we've got a AND model term
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found AND contraint term " + rawModelPart);
+      }
+
+      // get the model term
+      PModelPart modelPart = ((AXorModelPart)rawModelPart).getModelPart();
+
+      // get the model factor
+      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);
+      }
+
+      // get the LHS and RHS operands of the intersection
+      ModelExpression lhs = buildModelExpression(modelPart, aliasMap);
+      ModelExpression rhs = buildModelExpression(modelFactor, aliasMap);
+
+      // logger that we've resolved the operands
+      if (logger.isDebugEnabled()) {
+        logger.debug("Resolved LHS intersection operand " + lhs);
+        logger.debug("Resolved RHS intersection operand " + rhs);
+      }
+
+      // apply the intersection
+      modelExpression = new ModelPartition(lhs, rhs);
+    }
+
+    // end if
+    // we should not be returning null
+    if (modelExpression == null) {
+
+      throw new QueryException("Unable to parse ITQL model term into a valid model expression");
+    }
+
+    // end if
+    // logger that we've created a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Created model expression " + modelExpression);
+    }
+
+    // return the built up expression
+    return modelExpression;
+  }
+
+  // buildModelExpression()
+
+  /**
+   * Recursively builds a {@link org.mulgara.query.ModelExpression} from a
+   * {@link org.mulgara.itql.node.PModelFactor}.
+   *
+   * @param rawModelFactor a raw model factor from the parser
+   * @return a {@link org.mulgara.query.ModelExpression} suitable for use in
+   *      creating a {@link org.mulgara.query.Query}
+   * @throws QueryException if <code>rawModelExpression</code> does not
+   *      represent a valid query
+   * @throws URISyntaxException if the <code>rawModelExpression</code> contains
+   *      a resource whose text violates <a
+   *      href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
+   */
+  private static ModelExpression buildModelExpression(
+        PModelFactor rawModelFactor, Map<String,URI> aliasMap
+      ) throws QueryException, URISyntaxException {
+
+    // validate the rawModelFactor parameter
+    if (rawModelFactor == null) {
+
+      throw new IllegalArgumentException("Null \"rawModelFactor\" parameter");
+    }
+
+    // end if
+    // logger that we're building a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Building model expression from " + rawModelFactor);
+    }
+
+    // create a new model expression that we can return
+    ModelExpression modelExpression = null;
+
+    // drill down into the model term
+    if (rawModelFactor instanceof AResourceModelFactor) {
+
+      // logger that we've got a model model factor
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found resource model factor " + rawModelFactor);
+      }
+
+      // get the resource
+      String resource = ((AResourceModelFactor)rawModelFactor).getResource().getText();
+
+      // logger that we've found a resource
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found resource " + resource);
+      }
+
+      // this resource is what we're looking for
+      URI modelURI = URIUtil.convertToURI(resource, aliasMap);
+      modelExpression = new ModelResource(ServerURIHandler.removePort(modelURI));
+    } else if (rawModelFactor instanceof AExpressionModelFactor) {
+
+      // logger that we've got an expression model factor
+      if (logger.isDebugEnabled()) {
+        logger.debug("Found factor expression model factor " + rawModelFactor);
+      }
+
+      // get the model expression
+      PModelExpression embeddedModelExpression = ((AExpressionModelFactor)rawModelFactor).getModelExpression();
+
+      // logger that we're recursing with a model expression
+      if (logger.isDebugEnabled()) {
+        logger.debug("Recursing with model factor " + modelExpression);
+      }
+
+      // build the model expression
+      modelExpression = buildModelExpression(embeddedModelExpression, aliasMap);
+    }
+
+    // end if
+    // we should not be returning null
+    if (modelExpression == null) {
+
+      throw new QueryException("Unable to parse ITQL model factor " +
+        "into a valid model expression");
+    }
+
+    // end if
+    // logger that we've created a model expression
+    if (logger.isDebugEnabled()) {
+      logger.debug("Created model expression " + modelExpression);
+    }
+
+    // return the built up expression
+    return modelExpression;
+  }
+
+  // buildModelExpression()
+}
+
+
+// ModelExpressionBuilder

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,128 +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
- * Northrop Grumman Corporation. All Rights Reserved.
- *
- * This file is an original work and contains no Original Code.  It was
- * developed by Netymon Pty Ltd under contract to the Australian 
- * Commonwealth Government, Defense Science and Technology Organisation
- * under contract #4500507038 and is contributed back to the Kowari/Mulgara
- * Project as per clauses 4.1.3 and 4.1.4 of the above contract.
- *
- * Contributor(s): N/A.
- *
- * Copyright:
- *   The copyright on this file is held by:
- *     The Australian Commonwealth Government
- *     Department of Defense
- *   Developed by Netymon Pty Ltd
- * Copyright (C) 2006
- * The Australian Commonwealth Government
- * Department of Defense
- *
- * [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.util.ArrayList;
-import java.util.List;
-
-// Third party packages
-import org.apache.log4j.Logger; 
-
-// Generated packages
-import org.mulgara.itql.analysis.*;
-import org.mulgara.itql.node.*;
-
-/**
- * Create a list of objects to be associated with a predicate in a compound constraint.
- *
- * @created 2006-04-07
- *
- * @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.
- *      All rights reserved.
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ObjectListBuilder extends AnalysisAdapter {
-
-  private final static Logger logger = Logger.getLogger(ObjectListBuilder.class.getName());
-
-  private List objList;
-  /**
-   * Constructor.
-   */
-  public ObjectListBuilder() {
-    objList = new ArrayList();
-  }
-
-  public List getObjectList() {
-    return objList;
-  }
-
-  /**
-   * Used to accumulate predicate lists.
-   */
-  private void addObject(PElement obj) {
-    objList.add(obj);
-  }
-
-  public void caseAEo1ExistsOterm(AEo1ExistsOterm term) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found an Eo1 Exists Object Term: " + term);
-    }
-    term.getOterm().apply(this);
-  }
-
-  public void caseAEo2ExistsOterm(AEo2ExistsOterm term) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found an Eo2 Exists Object Term: " + term);
-    }
-    term.getExistsOterm().apply(this);
-    term.getOterm().apply(this);
-  }
-
-  public void caseAOtermOterm(AOtermOterm term) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found an Existential Object Term: " + term);
-    }
-
-    addObject(term.getObject());
-  }
-
-  public void defaultCase(Node node) {
-    if (logger.isDebugEnabled()) {
-      logger.debug("Found node in object builder: " + node + "::" + node.getClass());
-    }
-  }
-}
-

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/ObjectListBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,128 @@
+/*
+ * 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
+ * Northrop Grumman Corporation. All Rights Reserved.
+ *
+ * This file is an original work and contains no Original Code.  It was
+ * developed by Netymon Pty Ltd under contract to the Australian 
+ * Commonwealth Government, Defense Science and Technology Organisation
+ * under contract #4500507038 and is contributed back to the Kowari/Mulgara
+ * Project as per clauses 4.1.3 and 4.1.4 of the above contract.
+ *
+ * Contributor(s): N/A.
+ *
+ * Copyright:
+ *   The copyright on this file is held by:
+ *     The Australian Commonwealth Government
+ *     Department of Defense
+ *   Developed by Netymon Pty Ltd
+ * Copyright (C) 2006
+ * The Australian Commonwealth Government
+ * Department of Defense
+ *
+ * [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.util.ArrayList;
+import java.util.List;
+
+// Third party packages
+import org.apache.log4j.Logger; 
+
+// Generated packages
+import org.mulgara.itql.analysis.*;
+import org.mulgara.itql.node.*;
+
+/**
+ * Create a list of objects to be associated with a predicate in a compound constraint.
+ *
+ * @created 2006-04-07
+ *
+ * @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.
+ *      All rights reserved.
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class ObjectListBuilder extends AnalysisAdapter {
+
+  private final static Logger logger = Logger.getLogger(ObjectListBuilder.class.getName());
+
+  private List objList;
+  /**
+   * Constructor.
+   */
+  public ObjectListBuilder() {
+    objList = new ArrayList();
+  }
+
+  public List getObjectList() {
+    return objList;
+  }
+
+  /**
+   * Used to accumulate predicate lists.
+   */
+  private void addObject(PElement obj) {
+    objList.add(obj);
+  }
+
+  public void caseAEo1ExistsOterm(AEo1ExistsOterm term) {
+    if (logger.isDebugEnabled()) {
+      logger.debug("Found an Eo1 Exists Object Term: " + term);
+    }
+    term.getOterm().apply(this);
+  }
+
+  public void caseAEo2ExistsOterm(AEo2ExistsOterm term) {
+    if (logger.isDebugEnabled()) {
+      logger.debug("Found an Eo2 Exists Object Term: " + term);
+    }
+    term.getExistsOterm().apply(this);
+    term.getOterm().apply(this);
+  }
+
+  public void caseAOtermOterm(AOtermOterm term) {
+    if (logger.isDebugEnabled()) {
+      logger.debug("Found an Existential Object Term: " + term);
+    }
+
+    addObject(term.getObject());
+  }
+
+  public void defaultCase(Node node) {
+    if (logger.isDebugEnabled()) {
+      logger.debug("Found node in object builder: " + node + "::" + node.getClass());
+    }
+  }
+}
+

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -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.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 RuntimeException 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: trunk/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/SableCCInterpreter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -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 RuntimeException 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);
+
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,407 +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.itql;
-
-import java.net.URI;
-import java.util.HashMap;
-import java.util.Iterator;
-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 Map<URI,Connection> transConnections = new HashMap<URI,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 = null;
-      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();
-    }
-
-    assert lastMessage != null;
-
-    // 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 = transConnections.get(serverUri);
-      if (connection == null) {
-        connection = connectionFactory.newConnection(serverUri);
-        configureForTransaction(serverUri, 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 = null;
-    if (serverUri == null) {
-      connection = localStateConnection;
-    } else {
-      serverUri = ConnectionFactory.normalizeLocalUri(serverUri);
-      connection = transConnections.get(serverUri);
-      if (connection == null) {
-        connection = connectionFactory.newConnection(serverUri);
-        // update the connection if it needs to enter a current transaction
-        configureForTransaction(serverUri, 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(URI serverUri, 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.containsValue(connection);
-      transConnections.put(serverUri, 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.values().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: trunk/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlAutoInterpreter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,407 @@
+/**
+ * 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.HashMap;
+import java.util.Iterator;
+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 Map<URI,Connection> transConnections = new HashMap<URI,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 = null;
+      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();
+    }
+
+    assert lastMessage != null;
+
+    // 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 = transConnections.get(serverUri);
+      if (connection == null) {
+        connection = connectionFactory.newConnection(serverUri);
+        configureForTransaction(serverUri, 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 = null;
+    if (serverUri == null) {
+      connection = localStateConnection;
+    } else {
+      serverUri = ConnectionFactory.normalizeLocalUri(serverUri);
+      connection = transConnections.get(serverUri);
+      if (connection == null) {
+        connection = connectionFactory.newConnection(serverUri);
+        // update the connection if it needs to enter a current transaction
+        configureForTransaction(serverUri, 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(URI serverUri, 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.containsValue(connection);
+      transConnections.put(serverUri, 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.values().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;
+    }
+  }
+
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,100 +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.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: trunk/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlCommandSplitter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -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;
+  }
+
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,1583 +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.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.Export;
-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());
-
-  static {
-    // force initialization of static, unsynchronized variables inside these classes
-    new Parser(new Lexer2());
-  }
-
-  /** 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));
-    aliases.put(SKOS, URI.create(SKOS_NS));
-    aliases.put(FOAF, URI.create(FOAF_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();
-    resetInterpreter();
-
-    // 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;
-        String commandText = lexer.getCurrentCommand();
-  
-        // parse the command
-        Parser parser = new Parser(lexer);
-        commandTree = parser.parse();
-
-        // Build the command. This populates lastCommand
-        commandTree.apply(this);
-        lastCommand.setText(commandText);
-
-        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()) {
-
-      String commandText = lexer.getCurrentCommand();
-
-      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);
-        lastCommand.setText(commandText);
-        
-        // 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);
-    // This may not be accurate if there was more than one query, but if the lexer stopped short, we're stuck here.
-    lastCommand.setText(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);
-    }
-  }
-
-
-  /**
-   * Requests a list of current aliases.
-   *
-   * @param node the alias command
-   */
-  public void outAAliaslCommand(AAliaslCommand node) {
-
-    // log the command
-    if (logger.isDebugEnabled()) logger.debug("Processing alias list command " + node);
-
-    // Return an AST element, for reporting on what happened.
-    // Use a Help command, with the alias listing as the help text.
-    lastCommand = new Help(buildAliasList());
-  }
-
-  /**
-   * 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
-   */
-  @SuppressWarnings("deprecation")
-  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);
-  }
-
-  /**
-   * Exports the contents of a graph to a local or remote file.
-   *
-   * @param node the backup command
-   */
-  public void outAExportCommand(AExportCommand node) {
-    
-    // log the command
-    if (logger.isDebugEnabled()) logger.debug("Processing export command " + node);
-
-    // get constituents of the export command
-    URI sourceURI = toURI(node.getSource());
-    URI destinationURI = toURI(node.getDestination());
-    boolean locality = node.getLocality() != null && (node.getLocality() instanceof ALocalLocality);
-
-    lastCommand = new Export(sourceURI, destinationURI, locality);
-  }
-  
-  /**
-   * Restores the contents of a server from a file.
-   *
-   * @param node the restore command
-   */
-  @SuppressWarnings("deprecation")
-  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);
-  }
-
-
-  /**
-   * Writes the alias map as a set of URI/namespace pairs to a string for printing.
-   * @return A String containing all the alias mappings.
-   */
-  private String buildAliasList() {
-    StringBuilder buffer = new StringBuilder();
-    for (Map.Entry<String,URI> alias: getAliasMap().entrySet()) {
-      buffer.append(alias.getKey()).append(":  <").append(alias.getValue()).append(">\n");
-    }
-    return buffer.toString();
-  }
-
-
-  /**
-   * 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 static class Lexer2 extends Lexer {
-  
-    int commandCount = 0;
-    final LinkedList<Token> leftoverTokenList = new LinkedList<Token>();
-    StringBuilder buildingCommand = new StringBuilder();
-    LinkedList<String> commandQueue = new LinkedList<String>();
-    String currentCommand = null;
-
-    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) {
-          commandQueue.addLast(buildingCommand.toString());
-          buildingCommand = new StringBuilder();
-          t = new EOF();
-          commandCount++;
-          assert commandCount == commandQueue.size();
-        } else {
-          buildingCommand.append(t.getText());
-        }
-        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--;
-        currentCommand = commandQueue.remove();
-        assert commandCount == commandQueue.size();
-        return true;
-      }
-    }
-
-    public String getCurrentCommand() {
-      return currentCommand;
-    }
-  }
-
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlInterpreter.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,1583 @@
+/**
+ * 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.Export;
+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());
+
+  static {
+    // force initialization of static, unsynchronized variables inside these classes
+    new Parser(new Lexer2());
+  }
+
+  /** 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));
+    aliases.put(SKOS, URI.create(SKOS_NS));
+    aliases.put(FOAF, URI.create(FOAF_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();
+    resetInterpreter();
+
+    // 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;
+        String commandText = lexer.getCurrentCommand();
+  
+        // parse the command
+        Parser parser = new Parser(lexer);
+        commandTree = parser.parse();
+
+        // Build the command. This populates lastCommand
+        commandTree.apply(this);
+        lastCommand.setText(commandText);
+
+        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()) {
+
+      String commandText = lexer.getCurrentCommand();
+
+      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);
+        lastCommand.setText(commandText);
+        
+        // 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);
+    // This may not be accurate if there was more than one query, but if the lexer stopped short, we're stuck here.
+    lastCommand.setText(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);
+    }
+  }
+
+
+  /**
+   * Requests a list of current aliases.
+   *
+   * @param node the alias command
+   */
+  public void outAAliaslCommand(AAliaslCommand node) {
+
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing alias list command " + node);
+
+    // Return an AST element, for reporting on what happened.
+    // Use a Help command, with the alias listing as the help text.
+    lastCommand = new Help(buildAliasList());
+  }
+
+  /**
+   * 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
+   */
+  @SuppressWarnings("deprecation")
+  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);
+  }
+
+  /**
+   * Exports the contents of a graph to a local or remote file.
+   *
+   * @param node the backup command
+   */
+  public void outAExportCommand(AExportCommand node) {
+    
+    // log the command
+    if (logger.isDebugEnabled()) logger.debug("Processing export command " + node);
+
+    // get constituents of the export command
+    URI sourceURI = toURI(node.getSource());
+    URI destinationURI = toURI(node.getDestination());
+    boolean locality = node.getLocality() != null && (node.getLocality() instanceof ALocalLocality);
+
+    lastCommand = new Export(sourceURI, destinationURI, locality);
+  }
+  
+  /**
+   * Restores the contents of a server from a file.
+   *
+   * @param node the restore command
+   */
+  @SuppressWarnings("deprecation")
+  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);
+  }
+
+
+  /**
+   * Writes the alias map as a set of URI/namespace pairs to a string for printing.
+   * @return A String containing all the alias mappings.
+   */
+  private String buildAliasList() {
+    StringBuilder buffer = new StringBuilder();
+    for (Map.Entry<String,URI> alias: getAliasMap().entrySet()) {
+      buffer.append(alias.getKey()).append(":  <").append(alias.getValue()).append(">\n");
+    }
+    return buffer.toString();
+  }
+
+
+  /**
+   * 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 static class Lexer2 extends Lexer {
+  
+    int commandCount = 0;
+    final LinkedList<Token> leftoverTokenList = new LinkedList<Token>();
+    StringBuilder buildingCommand = new StringBuilder();
+    LinkedList<String> commandQueue = new LinkedList<String>();
+    String currentCommand = null;
+
+    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) {
+          commandQueue.addLast(buildingCommand.toString());
+          buildingCommand = new StringBuilder();
+          t = new EOF();
+          commandCount++;
+          assert commandCount == commandQueue.size();
+        } else {
+          buildingCommand.append(t.getText());
+        }
+        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--;
+        currentCommand = commandQueue.remove();
+        assert commandCount == commandQueue.size();
+        return true;
+      }
+    }
+
+    public String getCurrentCommand() {
+      return currentCommand;
+    }
+  }
+
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/TqlSession.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlSession.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlSession.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,666 +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.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.Logger;
-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 = "TQL> ";
-
-  /** 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 Logger log = Logger.getLogger(TqlSession.class);
-
-  /** 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;
-  
-  /** A flag to indicate that an executed command was complete */
-  private boolean incomplete = false;
-
-  /** The last command that was run. */
-  private String lastCommand = "";
-
-  /**
-   * 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;
-  }
-
-
-  /**
-   * Indicates if the last issued command was complete. If not, then a semicolon was not found
-   * to terminate the command.
-   * @return <code>false</code> only if the last command was complete. <code>true</code> if it completed.
-   */
-  boolean isCommandIncomplete() {
-    return incomplete;
-  }
-
-
-  /**
-   * 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();
-
-    boolean previouslyIncomplete = incomplete;
-
-    // presume ensuing commands are complete
-    incomplete = false;
-    for (String query: commandSplitter.split(command)) {
-      // clear out empty commands
-      if (incomplete) incomplete = false;
-
-      // check if we need to follow on
-      if (previouslyIncomplete) {
-        query = lastCommand + query;
-        previouslyIncomplete = false;
-      }
-      lastCommand = query + " ";
-
-      if (log.isDebugEnabled()) log.debug("Starting execution of command \"" + query + "\"");
-
-      // execute the command
-      if (!autoTql.executeCommand(query)) {
-        close();
-        return;
-      }
-      
-      String msg = autoTql.getLastMessage();
-      if (msg == null) {
-        if (log.isDebugEnabled()) log.debug("Need to follow on for an incomplete command.");
-        incomplete = true;
-        continue;
-      }
-
-      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(msg);
-
-      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);
-          
-          Exception e = autoTql.getLastException();
-          if (e != null) log.warn("Couldn't execute command", e);
-        }
-
-      }
-    } 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: trunk/src/jar/querylang/java/org/mulgara/itql/TqlSession.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlSession.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/TqlSession.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlSession.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,666 @@
+/*
+ * 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.Logger;
+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 = "TQL> ";
+
+  /** 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 Logger log = Logger.getLogger(TqlSession.class);
+
+  /** 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;
+  
+  /** A flag to indicate that an executed command was complete */
+  private boolean incomplete = false;
+
+  /** The last command that was run. */
+  private String lastCommand = "";
+
+  /**
+   * 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;
+  }
+
+
+  /**
+   * Indicates if the last issued command was complete. If not, then a semicolon was not found
+   * to terminate the command.
+   * @return <code>false</code> only if the last command was complete. <code>true</code> if it completed.
+   */
+  boolean isCommandIncomplete() {
+    return incomplete;
+  }
+
+
+  /**
+   * 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();
+
+    boolean previouslyIncomplete = incomplete;
+
+    // presume ensuing commands are complete
+    incomplete = false;
+    for (String query: commandSplitter.split(command)) {
+      // clear out empty commands
+      if (incomplete) incomplete = false;
+
+      // check if we need to follow on
+      if (previouslyIncomplete) {
+        query = lastCommand + query;
+        previouslyIncomplete = false;
+      }
+      lastCommand = query + " ";
+
+      if (log.isDebugEnabled()) log.debug("Starting execution of command \"" + query + "\"");
+
+      // execute the command
+      if (!autoTql.executeCommand(query)) {
+        close();
+        return;
+      }
+      
+      String msg = autoTql.getLastMessage();
+      if (msg == null) {
+        if (log.isDebugEnabled()) log.debug("Need to follow on for an incomplete command.");
+        incomplete = true;
+        continue;
+      }
+
+      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(msg);
+
+      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);
+          
+          Exception e = autoTql.getLastException();
+          if (e != null) log.warn("Couldn't execute command", e);
+        }
+
+      }
+    } 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(" ]");
+      }
+    }
+  }
+
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,778 +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;
-
-/**
- * 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.getKeyCode() == KeyEvent.VK_BACK_SPACE || 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.isCommandIncomplete() ? TqlSession.PS2 : 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: trunk/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/TqlSessionUI.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,778 @@
+/*
+ * 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.getKeyCode() == KeyEvent.VK_BACK_SPACE || 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.isCommandIncomplete() ? TqlSession.PS2 : 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();
+    }
+  }
+  
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/URIUtil.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/URIUtil.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/URIUtil.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,51 +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.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 RuntimeException("Bad URI syntax in resource", e);
-    }
-  }
-  
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/URIUtil.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/URIUtil.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/URIUtil.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/URIUtil.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -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 RuntimeException("Bad URI syntax in resource", e);
+    }
+  }
+  
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,199 +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;
-
-// Java 2 standard packages
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.List;
-
-// Third party packages
-import org.apache.log4j.Logger;
-
-// Automatically generated packages (SableCC)
-import org.mulgara.itql.analysis.AnalysisAdapter;
-import org.mulgara.itql.node.*;
-
-// Locally written packages
-import org.mulgara.query.*;
-import org.mulgara.query.rdf.URIReferenceImpl;
-
-
-/**
- * A implementation of SableCC's Adapter which creates list of variables
- * depending on the type of object given (visitor pattern).  Tied heavily to
- * the ItqlInterpreter.
- *
- * @created 2004-06-18
- *
- * @author Andrew Newman
- *
- * @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>
- */
-public class VariableBuilder extends AnalysisAdapter {
-
-  /** The logger */
-  private final static Logger logger = Logger.getLogger(VariableBuilder.class.getName());
-
-  /** Variable name generator for anonymous columns */
-  private VariableFactory variableFactory;
-
-  /** 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. */
-  private QueryException queryException = null;
-
-  /**
-   * The list of variables - these are mixed object types:
-   * ConstantValue, Variable, Count, SubQuery
-   */
-  private List<SelectElement> variableList;
-
-  /** 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(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())
-    ));
-  }
-
-
-  /**
-   * 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()))
-    ));
-  }
-
-
-  /**
-   * 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();
-
-    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);
-  }
-
-
-  /**
-   * Handle an aggregate element.  At the moment it handles both count and
-   * 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;
-
-      // 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(aggregateVariable, aggregateQuery));
-      } else if (aggregate instanceof ASubqueryAggregate) {
-        variableList.add(new Subquery(aggregateVariable, aggregateQuery));
-      } else {
-        throw new Error("Unsupported aggregate type: " + aggregate.getClass());
-      }
-    } catch (QueryException qe) {
-      queryException = qe;
-    } 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<SelectElement> getVariableList() throws QueryException, URISyntaxException {
-    try {
-      List<SelectElement> tmpVariableList = new ArrayList<SelectElement>(variableList);
-
-      if (uriException != null) throw uriException;
-      else if (queryException != null) throw queryException;
-      else return tmpVariableList;
-
-    } finally {
-      uriException = null;
-      queryException = null;
-      variableList.clear();
-    }
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/VariableBuilder.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,199 @@
+/*
+ * 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;
+
+// Java 2 standard packages
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
+
+// Third party packages
+import org.apache.log4j.Logger;
+
+// Automatically generated packages (SableCC)
+import org.mulgara.itql.analysis.AnalysisAdapter;
+import org.mulgara.itql.node.*;
+
+// Locally written packages
+import org.mulgara.query.*;
+import org.mulgara.query.rdf.URIReferenceImpl;
+
+
+/**
+ * A implementation of SableCC's Adapter which creates list of variables
+ * depending on the type of object given (visitor pattern).  Tied heavily to
+ * the ItqlInterpreter.
+ *
+ * @created 2004-06-18
+ *
+ * @author Andrew Newman
+ *
+ * @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>
+ */
+public class VariableBuilder extends AnalysisAdapter {
+
+  /** The logger */
+  private final static Logger logger = Logger.getLogger(VariableBuilder.class.getName());
+
+  /** Variable name generator for anonymous columns */
+  private VariableFactory variableFactory;
+
+  /** 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. */
+  private QueryException queryException = null;
+
+  /**
+   * The list of variables - these are mixed object types:
+   * ConstantValue, Variable, Count, SubQuery
+   */
+  private List<SelectElement> variableList;
+
+  /** 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(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())
+    ));
+  }
+
+
+  /**
+   * 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()))
+    ));
+  }
+
+
+  /**
+   * 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();
+
+    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);
+  }
+
+
+  /**
+   * Handle an aggregate element.  At the moment it handles both count and
+   * 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;
+
+      // 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(aggregateVariable, aggregateQuery));
+      } else if (aggregate instanceof ASubqueryAggregate) {
+        variableList.add(new Subquery(aggregateVariable, aggregateQuery));
+      } else {
+        throw new Error("Unsupported aggregate type: " + aggregate.getClass());
+      }
+    } catch (QueryException qe) {
+      queryException = qe;
+    } 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<SelectElement> getVariableList() throws QueryException, URISyntaxException {
+    try {
+      List<SelectElement> tmpVariableList = new ArrayList<SelectElement>(variableList);
+
+      if (uriException != null) throw uriException;
+      else if (queryException != null) throw queryException;
+      else return tmpVariableList;
+
+    } finally {
+      uriException = null;
+      queryException = null;
+      variableList.clear();
+    }
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,101 +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;
-
-// 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.*;
-import org.mulgara.query.rdf.*;
-import org.mulgara.server.Session;
-import org.mulgara.server.SessionFactory;
-import org.mulgara.server.driver.SessionFactoryFinder;
-import org.mulgara.server.driver.SessionFactoryFinderException;
-
-
-/**
- * A simple variable factory object.  Creates variables called "k" followed
- * by an incrementing variable value.
- *
- * @created 2004-06-18
- *
- * @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>
- */
-public class VariableFactoryImpl implements VariableFactory {
-
-  /**
-   * The logger
-   */
-  private final static Logger logger =
-      Logger.getLogger(VariableFactory.class.getName());
-
-  /**
-   * Index to keep track.
-   */
-  private int index = 0;
-
-  /**
-   * Returns a new variable an increment index.
-   *
-   * @return Variable a new variable.
-   */
-  public Variable newVariable() {
-    return new Variable("k" + Integer.toString(index++));
-  }
-
-  /**
-   * Reset the index to 0.
-   */
-  public void reset() {
-    index = 0;
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/VariableFactoryImpl.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,101 @@
+/*
+ * 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;
+
+// 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.*;
+import org.mulgara.query.rdf.*;
+import org.mulgara.server.Session;
+import org.mulgara.server.SessionFactory;
+import org.mulgara.server.driver.SessionFactoryFinder;
+import org.mulgara.server.driver.SessionFactoryFinderException;
+
+
+/**
+ * A simple variable factory object.  Creates variables called "k" followed
+ * by an incrementing variable value.
+ *
+ * @created 2004-06-18
+ *
+ * @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>
+ */
+public class VariableFactoryImpl implements VariableFactory {
+
+  /**
+   * The logger
+   */
+  private final static Logger logger =
+      Logger.getLogger(VariableFactory.class.getName());
+
+  /**
+   * Index to keep track.
+   */
+  private int index = 0;
+
+  /**
+   * Returns a new variable an increment index.
+   *
+   * @return Variable a new variable.
+   */
+  public Variable newVariable() {
+    return new Variable("k" + Integer.toString(index++));
+  }
+
+  /**
+   * Reset the index to 0.
+   */
+  public void reset() {
+    index = 0;
+  }
+}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/examples (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/examples)

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,151 +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.examples;
-
-// Logging
-import org.apache.log4j.*;
-
-// Internal packages.
-import org.mulgara.itql.ItqlInterpreterBean;
-import org.mulgara.query.Answer;
-
-/**
- * A simple Mulgara client to demonstrate the Mulgara java API. The client will print
- * out the contents of the model specified on the command line.
- *
- * @created 2002-11-02
- *
- * @author Ben Warren
- *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:16 $ by $Author: newmana $
- *
- * @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>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class SimpleClient {
-
-  /**
-   * Get line separator.
-   */
-  private static final String eol = System.getProperty("line.separator");
-
-  /**
-   * iTQL Bean used to query Mulgara
-   */
-  private ItqlInterpreterBean interpreter;
-
-  /**
-   * Public constructor.
-   */
-  public SimpleClient() {
-
-    // Initialise logging
-    BasicConfigurator.configure();
-    LogManager.getLoggerRepository().setThreshold(Level.OFF);
-
-    // Create the iTQL Bean to use for queries
-    interpreter = new ItqlInterpreterBean();
-  }
-
-  /**
-   * Runs this class from the command line.
-   *
-   * @param args Takes the name of the model to connect to and print out. eg
-   *      <code>rmi://hostname.domain/server1#</code>
-   */
-  public static void main(String[] args) {
-
-    if ( (args.length != 1) || (args[0].length() == 0)) {
-
-      System.out.println(eol + "Please specify the URI of the model to query." +
-          " eg rmi://hostname.domain/server1#" + eol);
-      System.exit(0);
-    }
-
-    SimpleClient client = new SimpleClient();
-    client.displayModel(args[0]);
-    client.close();
-  }
-
-  /**
-   * Prints out the contents of a model.
-   *
-   * @param modelName The name of the model query.
-   */
-  public void displayModel(String modelName) {
-
-    try {
-
-      // Query to select all subject-predicate-object statements from the model
-      String query =
-          "select $s $p $o from <" + modelName + "> where $s $p $o ;";
-
-      // Do the query
-      Answer answer = interpreter.executeQuery(query);
-
-      // Print out the results
-      System.out.println("\nQuery Results for <" + modelName + ">:" + eol);
-
-      answer.beforeFirst();
-
-      while (answer.next()) {
-
-        Object subject = answer.getObject(0);
-        Object predicate = answer.getObject(1);
-        Object object = answer.getObject(2);
-
-        System.out.println("Subject: " + subject + ", Predicate: " + predicate +
-            ", Object: " + object);
-      }
-      answer.close();
-
-      System.out.println();
-    }
-    catch (Exception e) {
-
-      System.out.println(eol + "An Exception occurred: " + eol + e);
-    }
-  }
-
-  /**
-   * Closes the underlying itql interpreter bean.
-   */
-  public void close() {
-    if (interpreter != null) {
-      interpreter.close();
-    }
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/examples/SimpleClient.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,151 @@
+/*
+ * 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.examples;
+
+// Logging
+import org.apache.log4j.*;
+
+// Internal packages.
+import org.mulgara.itql.ItqlInterpreterBean;
+import org.mulgara.query.Answer;
+
+/**
+ * A simple Mulgara client to demonstrate the Mulgara java API. The client will print
+ * out the contents of the model specified on the command line.
+ *
+ * @created 2002-11-02
+ *
+ * @author Ben Warren
+ *
+ * @version $Revision: 1.8 $
+ *
+ * @modified $Date: 2005/01/05 04:58:16 $ by $Author: newmana $
+ *
+ * @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>
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class SimpleClient {
+
+  /**
+   * Get line separator.
+   */
+  private static final String eol = System.getProperty("line.separator");
+
+  /**
+   * iTQL Bean used to query Mulgara
+   */
+  private ItqlInterpreterBean interpreter;
+
+  /**
+   * Public constructor.
+   */
+  public SimpleClient() {
+
+    // Initialise logging
+    BasicConfigurator.configure();
+    LogManager.getLoggerRepository().setThreshold(Level.OFF);
+
+    // Create the iTQL Bean to use for queries
+    interpreter = new ItqlInterpreterBean();
+  }
+
+  /**
+   * Runs this class from the command line.
+   *
+   * @param args Takes the name of the model to connect to and print out. eg
+   *      <code>rmi://hostname.domain/server1#</code>
+   */
+  public static void main(String[] args) {
+
+    if ( (args.length != 1) || (args[0].length() == 0)) {
+
+      System.out.println(eol + "Please specify the URI of the model to query." +
+          " eg rmi://hostname.domain/server1#" + eol);
+      System.exit(0);
+    }
+
+    SimpleClient client = new SimpleClient();
+    client.displayModel(args[0]);
+    client.close();
+  }
+
+  /**
+   * Prints out the contents of a model.
+   *
+   * @param modelName The name of the model query.
+   */
+  public void displayModel(String modelName) {
+
+    try {
+
+      // Query to select all subject-predicate-object statements from the model
+      String query =
+          "select $s $p $o from <" + modelName + "> where $s $p $o ;";
+
+      // Do the query
+      Answer answer = interpreter.executeQuery(query);
+
+      // Print out the results
+      System.out.println("\nQuery Results for <" + modelName + ">:" + eol);
+
+      answer.beforeFirst();
+
+      while (answer.next()) {
+
+        Object subject = answer.getObject(0);
+        Object predicate = answer.getObject(1);
+        Object object = answer.getObject(2);
+
+        System.out.println("Subject: " + subject + ", Predicate: " + predicate +
+            ", Object: " + object);
+      }
+      answer.close();
+
+      System.out.println();
+    }
+    catch (Exception e) {
+
+      System.out.println(eol + "An Exception occurred: " + eol + e);
+    }
+  }
+
+  /**
+   * Closes the underlying itql interpreter bean.
+   */
+  public void close() {
+    if (interpreter != null) {
+      interpreter.close();
+    }
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/itql/package.html
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/package.html	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/package.html	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,13 +0,0 @@
-<html>
-<head>
-<title>Interactive TQL</title>
-</head>
-<body>
-<abstract>
-Interactive TQL syntax.
-</abstract>
-<p>
-A command line interface to the Mulgara Metadata Store using interactive TQL syntax.
-</p>
-</body>
-</html>

Copied: trunk/src/jar/querylang/java/org/mulgara/itql/package.html (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/itql/package.html)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/itql/package.html	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/itql/package.html	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,13 @@
+<html>
+<head>
+<title>Interactive TQL</title>
+</head>
+<body>
+<abstract>
+Interactive TQL syntax.
+</abstract>
+<p>
+A command line interface to the Mulgara Metadata Store using interactive TQL syntax.
+</p>
+</body>
+</html>

Copied: trunk/src/jar/querylang/java/org/mulgara/store (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store)

Copied: trunk/src/jar/querylang/java/org/mulgara/store/jxunit (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit)

Deleted: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,104 +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.store.jxunit;
-
-// Java 2 standard packages
-import java.io.*;
-import java.net.URI;
-
-// 3rd party package
-import net.sourceforge.jxunit.*;
-
-/**
- * Test frame for file copying.
- *
- * @created 2004-11-15
- *
- * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
- *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:16 $
- *
- * @maintenanceAuthor $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>
- */
-public class CopyJX implements JXTestStep {
-
-  /**
-   * Parameter name of the source file
-   */
-  public final static String SOURCE = "sourceURI";
-
-  /**
-   * Parameter name of the destination file
-   */
-  public final static String DESTINATION = "destinationURI";
-
-  /**
-   * Execute this object.
-   *
-   * Clears the test model from the graph, then retrieve a
-   * filename from the testCase properties and load it as RDF. Results of each
-   * stage are stored back in the properties object.
-   *
-   * @param testCase The map object containing the properties.
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void eval(JXTestCase testCase) throws Exception {
-
-    JXProperties props = testCase.getProperties();
-    URI sourceURI      = new URI((String) props.get(SOURCE));
-    URI destinationURI = new URI((String) props.get(DESTINATION));
-
-    InputStream in = sourceURI.toURL().openStream();
-    OutputStream out =
-      new FileOutputStream(new File(destinationURI.toURL().getFile()));
-
-    // Copy from source to destination in 1K chunks
-    byte buffer[] = new byte[1024];
-    int length;
-    while ((length = in.read(buffer, 0, buffer.length)) != -1) {
-      out.write(buffer, 0, length);
-    }
-    assert length == -1;
-
-    out.close();
-    in.close();
-
-    // clear out the parameters for subsequent copies
-    props.remove(SOURCE);
-    props.remove(DESTINATION);
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/CopyJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,104 @@
+/*
+ * 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.store.jxunit;
+
+// Java 2 standard packages
+import java.io.*;
+import java.net.URI;
+
+// 3rd party package
+import net.sourceforge.jxunit.*;
+
+/**
+ * Test frame for file copying.
+ *
+ * @created 2004-11-15
+ *
+ * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
+ *
+ * @version $Revision: 1.8 $
+ *
+ * @modified $Date: 2005/01/05 04:58:16 $
+ *
+ * @maintenanceAuthor $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>
+ */
+public class CopyJX implements JXTestStep {
+
+  /**
+   * Parameter name of the source file
+   */
+  public final static String SOURCE = "sourceURI";
+
+  /**
+   * Parameter name of the destination file
+   */
+  public final static String DESTINATION = "destinationURI";
+
+  /**
+   * Execute this object.
+   *
+   * Clears the test model from the graph, then retrieve a
+   * filename from the testCase properties and load it as RDF. Results of each
+   * stage are stored back in the properties object.
+   *
+   * @param testCase The map object containing the properties.
+   * @throws Exception EXCEPTION TO DO
+   */
+  public void eval(JXTestCase testCase) throws Exception {
+
+    JXProperties props = testCase.getProperties();
+    URI sourceURI      = new URI((String) props.get(SOURCE));
+    URI destinationURI = new URI((String) props.get(DESTINATION));
+
+    InputStream in = sourceURI.toURL().openStream();
+    OutputStream out =
+      new FileOutputStream(new File(destinationURI.toURL().getFile()));
+
+    // Copy from source to destination in 1K chunks
+    byte buffer[] = new byte[1024];
+    int length;
+    while ((length = in.read(buffer, 0, buffer.length)) != -1) {
+      out.write(buffer, 0, length);
+    }
+    assert length == -1;
+
+    out.close();
+    in.close();
+
+    // clear out the parameters for subsequent copies
+    props.remove(SOURCE);
+    props.remove(DESTINATION);
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,99 +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.store.jxunit;
-
-
-// Java 2 standard packages
-// third party packages
-// Plugged In packages
-// third party packages
-import net.sourceforge.jxunit.*;  // Plugged In packages
-
-/**
- * Debug object for printing values in JXUnit tests.
- *
- * @created 2001-12-18
- *
- * @author <a href="http://staff.pisoftware.com/pag">Paul Gearon</a>
- *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:16 $
- *
- * @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
- *      Software Pty Ltd</A>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class DebugPrint implements JXTestStep {
-
-  /**
-   * Name of the print parameter
-   */
-  public final static String PRINT = "print";
-
-  /**
-   * Name of the label parameter
-   */
-  public final static String LABEL = "label";
-
-  /**
-   * Name of the debug paramter
-   */
-  public final static String DEBUG = "debug";
-
-  /**
-   * boolean value for the debug parameter
-   */
-  public final static String TRUE = "true";
-
-  /**
-   * Execute this object. Retrieves a string from the testCase properties and
-   * prints it to stdout.
-   *
-   * @param testCase The map object containing the properties.
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void eval(JXTestCase testCase) throws Exception {
-
-    JXProperties props = testCase.getProperties();
-    String debug = (String) props.get(DEBUG);
-
-    if ((debug != null) && debug.equals(TRUE)) {
-
-      String print = (String) props.get(PRINT);
-      String label = (String) props.get(LABEL);
-
-      System.out.println(label + ": " + print);
-    }
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/DebugPrint.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,99 @@
+/*
+ * 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.store.jxunit;
+
+
+// Java 2 standard packages
+// third party packages
+// Plugged In packages
+// third party packages
+import net.sourceforge.jxunit.*;  // Plugged In packages
+
+/**
+ * Debug object for printing values in JXUnit tests.
+ *
+ * @created 2001-12-18
+ *
+ * @author <a href="http://staff.pisoftware.com/pag">Paul Gearon</a>
+ *
+ * @version $Revision: 1.8 $
+ *
+ * @modified $Date: 2005/01/05 04:58:16 $
+ *
+ * @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
+ *      Software Pty Ltd</A>
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class DebugPrint implements JXTestStep {
+
+  /**
+   * Name of the print parameter
+   */
+  public final static String PRINT = "print";
+
+  /**
+   * Name of the label parameter
+   */
+  public final static String LABEL = "label";
+
+  /**
+   * Name of the debug paramter
+   */
+  public final static String DEBUG = "debug";
+
+  /**
+   * boolean value for the debug parameter
+   */
+  public final static String TRUE = "true";
+
+  /**
+   * Execute this object. Retrieves a string from the testCase properties and
+   * prints it to stdout.
+   *
+   * @param testCase The map object containing the properties.
+   * @throws Exception EXCEPTION TO DO
+   */
+  public void eval(JXTestCase testCase) throws Exception {
+
+    JXProperties props = testCase.getProperties();
+    String debug = (String) props.get(DEBUG);
+
+    if ((debug != null) && debug.equals(TRUE)) {
+
+      String print = (String) props.get(PRINT);
+      String label = (String) props.get(LABEL);
+
+      System.out.println(label + ": " + print);
+    }
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,187 +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.store.jxunit;
-
-// 3rd party package
-import net.sourceforge.jxunit.*;
-
-// Locally created package.
-import org.mulgara.itql.ItqlInterpreterBean;
-
-/**
- * Test frame for model creation using iTQL.
- *
- * @created 2001-12-18
- *
- * @author <a href="http://staff.pisoftware.com/pag">Paul Gearon</a>
- *
- * @version $Revision: 1.9 $
- *
- * @modified $Date: 2005/07/03 13:03:12 $
- *
- * @maintenanceAuthor $Author: pgearon $
- *
- * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
- *
- * @copyright &copy; 2001-2003 <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 LoadDataJX implements JXTestStep {
-
-  /**
-   * Get line separator.
-   */
-  private static final String eol = System.getProperty("line.separator");
-
-  /**
-   * Parameter name of the model name
-   */
-  public final static String MODEL = "modelName";
-
-  /**
-   * Parameter name of the load command
-   */
-  public final static String COMMAND = "loadCommand";
-
-  /**
-   * Parameter name of the type of model
-   */
-  public final static String TYPE = "modelType";
-
-  /**
-   * Parameter name of the results of operations performed prior to loading
-   */
-  public final static String DROP_RESULT = "preCreateResult";
-
-  /**
-   * Parameter name of the results of the model creation
-   */
-  public final static String CREATE_RESULT = "createResult";
-
-  /**
-   * Parameter name of the results of the load operation
-   */
-  public final static String LOAD_RESULT = "loadResult";
-
-  /**
-   * Parameter name of the "Clear Model" command
-   */
-  public final static String CLEAR = "clearModel";
-
-  /**
-   * Execute this object. Clears the test model from the graph, then retrieve a
-   * filename from the testCase properties and load it as RDF. Results of each
-   * stage are stored back in the properties object.
-   *
-   * @param testCase The map object containing the properties.
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void eval(JXTestCase testCase) throws Exception {
-
-    JXProperties props = testCase.getProperties();
-    String model = (String) props.get(MODEL);
-
-    // Performing a load is optional
-    String cmd = "";
-
-    if (props.get(COMMAND) != null) {
-
-      cmd = (String) props.get(COMMAND);
-    }
-
-    // The type of model is optional
-    String type = "";
-
-    if (props.get(TYPE) != null) {
-
-      type = (String) props.get(TYPE);
-    }
-
-    String dropResult = null;
-
-    ItqlInterpreterBean iTQL = new ItqlInterpreterBean();
-    try {
-
-      boolean clear = true;
-
-      if (props.get(CLEAR) != null) {
-
-        // anything that is not "true" is considered "false"
-        clear = ((String) props.get(CLEAR)).equalsIgnoreCase("true");
-      }
-
-      if (clear) {
-        // Attempt to drop the model - may not be successful if model does not exist
-        try {
-
-          dropResult = iTQL.executeQueryToString("drop <" + model + "> ;");
-        }
-        catch (Exception ex) {
-
-          System.out.println("Unable to drop model - may have not existed");
-        }
-      }
-
-      // Create the model - optional model type
-      String createResult = "";
-
-      if (type.equals("")) {
-
-        createResult = iTQL.executeQueryToString("create <" + model + "> ;");
-      }
-      else {
-
-        createResult =
-            iTQL.executeQueryToString("create <" + model + "> " + "<" + type +
-            "> ;");
-      }
-
-      // Execute the command if supplied
-      String cmdResult = "";
-
-      if (!cmd.equals("")) {
-
-        cmdResult = iTQL.executeQueryToString(cmd);
-      }
-
-      props.put(DROP_RESULT, dropResult);
-      props.put(CREATE_RESULT, createResult + eol);
-      props.put(LOAD_RESULT, cmdResult + eol);
-
-    } finally {
-      iTQL.close();
-    }
-
-    // clear out the parameters for additional loads
-    props.remove(COMMAND);
-    props.remove(TYPE);
-    props.remove(MODEL);
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/LoadDataJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,187 @@
+/*
+ * 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.store.jxunit;
+
+// 3rd party package
+import net.sourceforge.jxunit.*;
+
+// Locally created package.
+import org.mulgara.itql.ItqlInterpreterBean;
+
+/**
+ * Test frame for model creation using iTQL.
+ *
+ * @created 2001-12-18
+ *
+ * @author <a href="http://staff.pisoftware.com/pag">Paul Gearon</a>
+ *
+ * @version $Revision: 1.9 $
+ *
+ * @modified $Date: 2005/07/03 13:03:12 $
+ *
+ * @maintenanceAuthor $Author: pgearon $
+ *
+ * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
+ *
+ * @copyright &copy; 2001-2003 <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 LoadDataJX implements JXTestStep {
+
+  /**
+   * Get line separator.
+   */
+  private static final String eol = System.getProperty("line.separator");
+
+  /**
+   * Parameter name of the model name
+   */
+  public final static String MODEL = "modelName";
+
+  /**
+   * Parameter name of the load command
+   */
+  public final static String COMMAND = "loadCommand";
+
+  /**
+   * Parameter name of the type of model
+   */
+  public final static String TYPE = "modelType";
+
+  /**
+   * Parameter name of the results of operations performed prior to loading
+   */
+  public final static String DROP_RESULT = "preCreateResult";
+
+  /**
+   * Parameter name of the results of the model creation
+   */
+  public final static String CREATE_RESULT = "createResult";
+
+  /**
+   * Parameter name of the results of the load operation
+   */
+  public final static String LOAD_RESULT = "loadResult";
+
+  /**
+   * Parameter name of the "Clear Model" command
+   */
+  public final static String CLEAR = "clearModel";
+
+  /**
+   * Execute this object. Clears the test model from the graph, then retrieve a
+   * filename from the testCase properties and load it as RDF. Results of each
+   * stage are stored back in the properties object.
+   *
+   * @param testCase The map object containing the properties.
+   * @throws Exception EXCEPTION TO DO
+   */
+  public void eval(JXTestCase testCase) throws Exception {
+
+    JXProperties props = testCase.getProperties();
+    String model = (String) props.get(MODEL);
+
+    // Performing a load is optional
+    String cmd = "";
+
+    if (props.get(COMMAND) != null) {
+
+      cmd = (String) props.get(COMMAND);
+    }
+
+    // The type of model is optional
+    String type = "";
+
+    if (props.get(TYPE) != null) {
+
+      type = (String) props.get(TYPE);
+    }
+
+    String dropResult = null;
+
+    ItqlInterpreterBean iTQL = new ItqlInterpreterBean();
+    try {
+
+      boolean clear = true;
+
+      if (props.get(CLEAR) != null) {
+
+        // anything that is not "true" is considered "false"
+        clear = ((String) props.get(CLEAR)).equalsIgnoreCase("true");
+      }
+
+      if (clear) {
+        // Attempt to drop the model - may not be successful if model does not exist
+        try {
+
+          dropResult = iTQL.executeQueryToString("drop <" + model + "> ;");
+        }
+        catch (Exception ex) {
+
+          System.out.println("Unable to drop model - may have not existed");
+        }
+      }
+
+      // Create the model - optional model type
+      String createResult = "";
+
+      if (type.equals("")) {
+
+        createResult = iTQL.executeQueryToString("create <" + model + "> ;");
+      }
+      else {
+
+        createResult =
+            iTQL.executeQueryToString("create <" + model + "> " + "<" + type +
+            "> ;");
+      }
+
+      // Execute the command if supplied
+      String cmdResult = "";
+
+      if (!cmd.equals("")) {
+
+        cmdResult = iTQL.executeQueryToString(cmd);
+      }
+
+      props.put(DROP_RESULT, dropResult);
+      props.put(CREATE_RESULT, createResult + eol);
+      props.put(LOAD_RESULT, cmdResult + eol);
+
+    } finally {
+      iTQL.close();
+    }
+
+    // clear out the parameters for additional loads
+    props.remove(COMMAND);
+    props.remove(TYPE);
+    props.remove(MODEL);
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,135 +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.store.jxunit;
-
-// 3rd party package
-import net.sourceforge.jxunit.*;
-
-// Locally created package.
-import org.mulgara.itql.ItqlInterpreterBean;
-
-/**
- * Test frame for iTQL queries.
- *
- * @created 2001-12-18
- *
- * @author <a href="http://staff.pisoftware.com/pag">Paul Gearon</a>
- *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:16 $
- *
- * @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
- *      Software Pty Ltd</A>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class QueryJX implements JXTestStep {
-
-  /**
-   * Get line separator.
-   */
-  private static final String eol = System.getProperty("line.separator");
-
-  /**
-   * Name of the query command parameter
-   */
-  public final static String QUERY = "query";
-
-  /**
-   * Parameter name of the results of the command
-   */
-  public final static String RESULT = "queryResult";
-
-  /**
-   * Parameter name of the time flag
-   */
-  public final static String TIME = "time";
-
-  /**
-   * Name of the queryName command parameter
-   */
-  public final static String QUERY_NAME = "queryName";
-
-  /**
-   * Execute this object. Retrieves a string from the testCase properties and
-   * executes it as an iTQL command, returning the results in the testCase
-   * object.
-   *
-
-   * @param testCase The map object containing the properties.
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void eval(JXTestCase testCase) throws Exception {
-
-    JXProperties props = testCase.getProperties();
-    String query = (String) props.get(QUERY);
-
-    boolean time = false;
-
-    if (props.getString(TIME) != null) {
-
-      time = Boolean.valueOf(props.getString(TIME)).booleanValue();
-    }
-
-    String queryName = query + eol;
-
-    if (props.getString(QUERY_NAME) != null) {
-
-      queryName = props.getString(QUERY_NAME);
-    }
-
-    ItqlInterpreterBean iTQL = new ItqlInterpreterBean();
-
-    long start = System.currentTimeMillis();
-    String queryResult = "";
-
-    try {
-
-      queryResult = iTQL.executeQueryToString(query);
-    } catch (Exception ex) {
-
-      queryResult = ex.getMessage();
-    } finally {
-      iTQL.close();
-    }
-
-    if (time) {
-
-      System.out.println(eol + "<" + queryName + "> query has taken " +
-        (System.currentTimeMillis() - start) + " milliseconds to execute." + eol);
-    }
-
-    props.put(RESULT, queryResult + eol);
-    props.remove(QUERY_NAME);
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/QueryJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,135 @@
+/*
+ * 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.store.jxunit;
+
+// 3rd party package
+import net.sourceforge.jxunit.*;
+
+// Locally created package.
+import org.mulgara.itql.ItqlInterpreterBean;
+
+/**
+ * Test frame for iTQL queries.
+ *
+ * @created 2001-12-18
+ *
+ * @author <a href="http://staff.pisoftware.com/pag">Paul Gearon</a>
+ *
+ * @version $Revision: 1.8 $
+ *
+ * @modified $Date: 2005/01/05 04:58:16 $
+ *
+ * @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
+ *      Software Pty Ltd</A>
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class QueryJX implements JXTestStep {
+
+  /**
+   * Get line separator.
+   */
+  private static final String eol = System.getProperty("line.separator");
+
+  /**
+   * Name of the query command parameter
+   */
+  public final static String QUERY = "query";
+
+  /**
+   * Parameter name of the results of the command
+   */
+  public final static String RESULT = "queryResult";
+
+  /**
+   * Parameter name of the time flag
+   */
+  public final static String TIME = "time";
+
+  /**
+   * Name of the queryName command parameter
+   */
+  public final static String QUERY_NAME = "queryName";
+
+  /**
+   * Execute this object. Retrieves a string from the testCase properties and
+   * executes it as an iTQL command, returning the results in the testCase
+   * object.
+   *
+
+   * @param testCase The map object containing the properties.
+   * @throws Exception EXCEPTION TO DO
+   */
+  public void eval(JXTestCase testCase) throws Exception {
+
+    JXProperties props = testCase.getProperties();
+    String query = (String) props.get(QUERY);
+
+    boolean time = false;
+
+    if (props.getString(TIME) != null) {
+
+      time = Boolean.valueOf(props.getString(TIME)).booleanValue();
+    }
+
+    String queryName = query + eol;
+
+    if (props.getString(QUERY_NAME) != null) {
+
+      queryName = props.getString(QUERY_NAME);
+    }
+
+    ItqlInterpreterBean iTQL = new ItqlInterpreterBean();
+
+    long start = System.currentTimeMillis();
+    String queryResult = "";
+
+    try {
+
+      queryResult = iTQL.executeQueryToString(query);
+    } catch (Exception ex) {
+
+      queryResult = ex.getMessage();
+    } finally {
+      iTQL.close();
+    }
+
+    if (time) {
+
+      System.out.println(eol + "<" + queryName + "> query has taken " +
+        (System.currentTimeMillis() - start) + " milliseconds to execute." + eol);
+    }
+
+    props.put(RESULT, queryResult + eol);
+    props.remove(QUERY_NAME);
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,118 +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.store.jxunit;
-
-// 3rd party package
-import net.sourceforge.jxunit.*;
-
-// Locally created package.
-import org.mulgara.itql.ItqlInterpreterBean;
-
-/**
- * Test frame for restoring a database
- *
- * @created 2001-12-18
- *
- * @author <a href="http://staff.pisoftware.com/tate">Tate Jones</a>
- *
- * @version $Revision: 1.8 $
- *
- * @modified $Date: 2005/01/05 04:58:16 $
- *
- * @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
- *      Software Pty Ltd</A>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class RestoreDataJX implements JXTestStep {
-
-  /**
-   * Parameter name of the server name
-   */
-  public final static String SERVER = "server";
-
-  /**
-   * Parameter name of the file name
-   */
-  public final static String FILE = "file";
-
-  /**
-   * Parameter name of the time flag
-   */
-  public final static String TIME = "time";
-
-  /**
-   * Supplied a valid server name and a file this method will restore a Mulgara
-   * database.
-   *
-   * @param testCase PARAMETER TO DO
-   * @throws Exception EXCEPTION TO DO
-   */
-  public void eval(JXTestCase testCase) throws Exception {
-
-    JXProperties props = testCase.getProperties();
-
-    String server = (String) props.get(SERVER);
-    String file = (String) props.get(FILE);
-
-    boolean time = false;
-
-    if (props.getString(TIME) != null) {
-
-      time = Boolean.valueOf(props.getString(TIME)).booleanValue();
-    }
-
-    ItqlInterpreterBean iTQL = new ItqlInterpreterBean();
-
-    System.out.println("Restoring Mulgara database from " + file +
-      " please wait...");
-
-    long start = System.currentTimeMillis();
-    try {
-      iTQL.executeQueryToString(
-          "restore <" + server + "> from <" + file + ">;"
-      );
-    } finally {
-      iTQL.close();
-    }
-
-    if (time) {
-
-      System.out.println("Time to restore " + file + " was " +
-        ((System.currentTimeMillis() - start) / 1000L) + " seconds");
-    }
-
-    // clear out the parameters for additional restore
-    props.remove(SERVER);
-    props.remove(FILE);
-  }
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/RestoreDataJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,118 @@
+/*
+ * 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.store.jxunit;
+
+// 3rd party package
+import net.sourceforge.jxunit.*;
+
+// Locally created package.
+import org.mulgara.itql.ItqlInterpreterBean;
+
+/**
+ * Test frame for restoring a database
+ *
+ * @created 2001-12-18
+ *
+ * @author <a href="http://staff.pisoftware.com/tate">Tate Jones</a>
+ *
+ * @version $Revision: 1.8 $
+ *
+ * @modified $Date: 2005/01/05 04:58:16 $
+ *
+ * @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
+ *      Software Pty Ltd</A>
+ *
+ * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
+ */
+public class RestoreDataJX implements JXTestStep {
+
+  /**
+   * Parameter name of the server name
+   */
+  public final static String SERVER = "server";
+
+  /**
+   * Parameter name of the file name
+   */
+  public final static String FILE = "file";
+
+  /**
+   * Parameter name of the time flag
+   */
+  public final static String TIME = "time";
+
+  /**
+   * Supplied a valid server name and a file this method will restore a Mulgara
+   * database.
+   *
+   * @param testCase PARAMETER TO DO
+   * @throws Exception EXCEPTION TO DO
+   */
+  public void eval(JXTestCase testCase) throws Exception {
+
+    JXProperties props = testCase.getProperties();
+
+    String server = (String) props.get(SERVER);
+    String file = (String) props.get(FILE);
+
+    boolean time = false;
+
+    if (props.getString(TIME) != null) {
+
+      time = Boolean.valueOf(props.getString(TIME)).booleanValue();
+    }
+
+    ItqlInterpreterBean iTQL = new ItqlInterpreterBean();
+
+    System.out.println("Restoring Mulgara database from " + file +
+      " please wait...");
+
+    long start = System.currentTimeMillis();
+    try {
+      iTQL.executeQueryToString(
+          "restore <" + server + "> from <" + file + ">;"
+      );
+    } finally {
+      iTQL.close();
+    }
+
+    if (time) {
+
+      System.out.println("Time to restore " + file + " was " +
+        ((System.currentTimeMillis() - start) / 1000L) + " seconds");
+    }
+
+    // clear out the parameters for additional restore
+    props.remove(SERVER);
+    props.remove(FILE);
+  }
+}

Deleted: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java
===================================================================
--- branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,80 +0,0 @@
-package org.mulgara.store.jxunit;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import net.sourceforge.jxunit.JXProperties;
-import net.sourceforge.jxunit.JXTestCase;
-import net.sourceforge.jxunit.JXTestStep;
-
-/**
-* @created 2006-07-15
-*
-* @author Brian Sletten
-*
-* @version $Revision: 1.0 $
-*
-*/
-public class TimeZoneSubstituteJX implements JXTestStep {
-	
-	// Names of properties to pull out of the JXProperties class
-	
-	/* The date to be converted */
-	public final static String TIMEDATE = "timedate";
-	
-	/* The token to substitute */
-	public final static String TOKEN = "token";
-	
-	/* The template document to substitute the token in */
-	public final static String TEMPLATE = "template";
-	
-	/* The actual results from the query */
-	public final static String QUERYRESULT = "queryResult";
-	
-	/* The property to set on success */
-	public final static String PROPERTY= "returnProperty";
-
-	public void eval(JXTestCase testCase) throws Throwable {
-		JXProperties props = testCase.getProperties();
-
-		boolean success = false;
-		
-		/* Retrieve each of the properties we are expecting.
-		   Throw an exception if any are missing */
-		
-		String timedate = checkGetValue( props, TIMEDATE );
-		String token = checkGetValue( props, TOKEN );
-		String template = checkGetValue( props, TEMPLATE );
-		String queryResult = checkGetValue( props, QUERYRESULT );
-		String returnProperty = checkGetValue( props, PROPERTY );
-		
-		/* Parse the datetime to substitute and convert it to the local timezone */
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-		Date d = sdf.parse( timedate );
-		
-		/* Convert it to the expected format */
-		sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss" );
-		String localTime = sdf.format(d);
-		
-		/* Replace the token and see if it matches the results */
-		String replaced = template.replace( token, localTime );
-		success = queryResult.equals( replaced );
-
-		if( success ) {
-			props.put( returnProperty, "true" );
-		} 
-	}
-
-	/* Retrieve the specified property and complain if it doesn't exist
-	   by throwing an IllegalStateException */
-	
-	private String checkGetValue( JXProperties props, String propertyName ) {
-		String retValue = props.getString( propertyName );
-		
-		if( retValue == null ) {
-			throw new IllegalStateException("Missing expected property: " + propertyName );
-		}
-		
-		return retValue;
-	}
-}

Copied: trunk/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java (from rev 1207, branches/mgr-143/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java)
===================================================================
--- trunk/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java	                        (rev 0)
+++ trunk/src/jar/querylang/java/org/mulgara/store/jxunit/TimeZoneSubstituteJX.java	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,80 @@
+package org.mulgara.store.jxunit;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import net.sourceforge.jxunit.JXProperties;
+import net.sourceforge.jxunit.JXTestCase;
+import net.sourceforge.jxunit.JXTestStep;
+
+/**
+* @created 2006-07-15
+*
+* @author Brian Sletten
+*
+* @version $Revision: 1.0 $
+*
+*/
+public class TimeZoneSubstituteJX implements JXTestStep {
+	
+	// Names of properties to pull out of the JXProperties class
+	
+	/* The date to be converted */
+	public final static String TIMEDATE = "timedate";
+	
+	/* The token to substitute */
+	public final static String TOKEN = "token";
+	
+	/* The template document to substitute the token in */
+	public final static String TEMPLATE = "template";
+	
+	/* The actual results from the query */
+	public final static String QUERYRESULT = "queryResult";
+	
+	/* The property to set on success */
+	public final static String PROPERTY= "returnProperty";
+
+	public void eval(JXTestCase testCase) throws Throwable {
+		JXProperties props = testCase.getProperties();
+
+		boolean success = false;
+		
+		/* Retrieve each of the properties we are expecting.
+		   Throw an exception if any are missing */
+		
+		String timedate = checkGetValue( props, TIMEDATE );
+		String token = checkGetValue( props, TOKEN );
+		String template = checkGetValue( props, TEMPLATE );
+		String queryResult = checkGetValue( props, QUERYRESULT );
+		String returnProperty = checkGetValue( props, PROPERTY );
+		
+		/* Parse the datetime to substitute and convert it to the local timezone */
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
+		Date d = sdf.parse( timedate );
+		
+		/* Convert it to the expected format */
+		sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss" );
+		String localTime = sdf.format(d);
+		
+		/* Replace the token and see if it matches the results */
+		String replaced = template.replace( token, localTime );
+		success = queryResult.equals( replaced );
+
+		if( success ) {
+			props.put( returnProperty, "true" );
+		} 
+	}
+
+	/* Retrieve the specified property and complain if it doesn't exist
+	   by throwing an IllegalStateException */
+	
+	private String checkGetValue( JXProperties props, String propertyName ) {
+		String retValue = props.getString( propertyName );
+		
+		if( retValue == null ) {
+			throw new IllegalStateException("Missing expected property: " + propertyName );
+		}
+		
+		return retValue;
+	}
+}

Deleted: trunk/src/jar/querylang/querylang-build.properties
===================================================================
--- branches/mgr-143/src/jar/querylang/querylang-build.properties	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/querylang-build.properties	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,15 +0,0 @@
-#
-# Properties used by the QueryLang module
-#
-
-# Module Name
-querylang.name = QueryLanguage
-
-# General module properties
-querylang.conf.dir      = ${conf.dir}
-querylang.src.dir       = ${jar.src.dir}/querylang
-querylang.obj.dir       = ${jar.obj.dir}/querylang
-querylang.dist.dir      = ${bin.dir}
-querylang.test.dir      = ${test.dir}/querylang
-querylang.jxtest.dir    = ${jxtest.dir}/querylang
-querylang.jar           = querylang-base-${mulgara-version}.jar

Copied: trunk/src/jar/querylang/querylang-build.properties (from rev 1207, branches/mgr-143/src/jar/querylang/querylang-build.properties)
===================================================================
--- trunk/src/jar/querylang/querylang-build.properties	                        (rev 0)
+++ trunk/src/jar/querylang/querylang-build.properties	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,15 @@
+#
+# Properties used by the QueryLang module
+#
+
+# Module Name
+querylang.name = QueryLanguage
+
+# General module properties
+querylang.conf.dir      = ${conf.dir}
+querylang.src.dir       = ${jar.src.dir}/querylang
+querylang.obj.dir       = ${jar.obj.dir}/querylang
+querylang.dist.dir      = ${bin.dir}
+querylang.test.dir      = ${test.dir}/querylang
+querylang.jxtest.dir    = ${jxtest.dir}/querylang
+querylang.jar           = querylang-base-${mulgara-version}.jar

Copied: trunk/src/jar/querylang/sablecc (from rev 1207, branches/mgr-143/src/jar/querylang/sablecc)

Deleted: trunk/src/jar/querylang/sablecc/itql.grammar
===================================================================
--- branches/mgr-143/src/jar/querylang/sablecc/itql.grammar	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/querylang/sablecc/itql.grammar	2008-08-30 07:33:19 UTC (rev 1208)
@@ -1,329 +0,0 @@
-Package org.mulgara.itql;
-
-/*
- * iTQL (SableCC grammar)
- */
-
-Helpers
-  character  = [0..0xFFFF];
-  letter     = ['a'..'z'] | ['A'..'Z'];
-  digit      = ['0'..'9'];
-  tab        = 9;
-  lf         = 10;
-  cr         = 13;
-  sl         = 47;
-  whitespace = ' ' | tab | lf | cr;
-  nonblank   = [33..126];
-  nonquote   = [character - [39 + '\']];
-  nonslash   = [[33..126] - sl];
-  urlchar    = [character - '>'];
-
-States
-  def,  /* default state */
-  com,  /* comment */
-  esc,  /* escaping character in quoted literal with '\' */
-  lit,  /* quoted literal */
-  begres,  /* start of tagged resource */
-  endres,  /* end of tagged resource */
-  var,  /* escaping variable name with '$' */
-  lng;  /* language code */
-
-Tokens
-  {def}                alias       = 'alias';
-  {def}                and         = 'and';
-  {def}                apply       = 'apply';
-  {def}                as          = 'as';
-  {def}                asc         = 'asc';
-  {def}                autocommit  = 'autocommit';
-  {def}                backup      = 'backup';
-  {def}                base        = 'base';
-  {def}                by          = 'by';
-  {def}                commit      = 'commit';
-  {def}                count       = 'count';
-  {def}                create      = 'create';
-  {def}                delete      = 'delete';
-  {def}                desc        = 'desc';
-  {def}                directory   = 'directory';
-  {def}                drop        = 'drop';
-  {def}                echo        = 'echo';
-  {def}                execute     = 'execute';
-  {def}                exclude     = 'exclude';
-  {def}                export      = 'export';
-  {def}                from        = 'from';
-  {def}                help        = 'help';
-  {def}                in          = 'in';
-  {def}                insert      = 'insert';
-  {def}                into        = 'into';
-  {def}                limit       = 'limit';
-  {def}                load        = 'load';
-  {def}                minus       = 'minus';
-  {def}                off         = 'off';
-  {def}                offset      = 'offset';
-  {def}                or          = 'or';
-  {def}                order       = 'order';
-  {def}                on          = 'on';
-  {def}                quit        = 'quit';
-  {def}                restore     = 'restore';
-  {def}                rollback    = 'rollback';
-  {def}                select      = 'select';
-  {def}                set         = 'set';
-  {def}                statistics  = 'statistics';
-  {def}                stoponerror = 'stoponerror';
-  {def}                su          = 'su';
-  {def}                subquery    = 'subquery';
-  {def}                threshold   = 'threshold';
-  {def}                time        = 'time';
-  {def}                to          = 'to';
-  {def}                trans       = 'trans';
-  {def}                walk        = 'walk';
-  {def}                where       = 'where';
-  {def}                having      = 'having';
-  {def}                xor         = 'xor';
-  {def}                local       = 'local';
-  {def}                remote      = 'remote';
-
-
-  {def, var->def}      identifier = letter (letter | digit | '_' | '$' )*;
-  {def}                blank      = whitespace+;
-  {def->com}           hash        = '#';
-  {com}                comment    = [character - [lf + cr]];
-  {com->def}           endcomment = (lf | cr)+;
-  {def}                terminator = ';';
-  {def}                lpar       = '(';
-  {def}                rpar       = ')';
-  {def->begres}        url        = '<';
-  {endres->def}        endurl     = '>';
-  {def}                datatypeprefix = '^^';
-  {def->lng}           languageprefix = '@';
-  {def->var}           variableprefix = ('$' | '?');
-  {def}                number     = digit+;
-  {def}                float      = digit+ ('.' digit*) | ('.' digit+);
-  {lng->def}           langid      = letter letter | letter letter '-' letter letter;
-
-  {begres->endres}     resource    = urlchar*;
-  {def->lit, lit->def} quote       = 39;  /* ' */
-  {lit->esc}           escape      = '\';
-  {esc->lit}           escapedtext = character;
-  {lit}                text        = nonquote+;
-
-  {def}                lbrace     = '{';
-  {def}                rbrace     = '}';
-  {def}                lbracket   = '[';
-  {def}                rbracket   = ']';
-  {def}                colon      = ':';
-  {def}                comma      = ',';
-
-Ignored Tokens
-  blank, comment, escape, endcomment, endurl, hash, url;
-
-Productions
-  start =
-    {command} command? ;
-
-  command =
-    {alias}     alias [target]:resource as [prefix]:identifier               |
-    {aliasl}    alias                                                        |
-    {apply}     apply [rules]:resource to [base]:resource [destination]:resource? |
-    {backup}    backup [source]:resource to [locality]:locality? [destination]:resource |
-    {commit}    commit                                                       |
-    {create}    create [model]:resource [model_type]:resource?               |
-    {delete}    delete triple_factor from resource                           |
-    {directory} directory resource                                           |
-    {drop}      drop resource                                                |
-    {execute}   execute resource                                             |
-    {export}    export [source]:resource to [locality]:locality? [destination]:resource |
-    {help}      help command_prefix                                          |
-    {insert}    insert triple_factor into resource                           |
-    {load}      load [locality]:locality? [source]:resource into [destination]:resource |
-    {quit}      quit                                                         |
-    {restore}   restore [destination]:resource from [locality]:locality? [source]:resource |
-    {rollback}  rollback                                                     |
-    {select}    query                                                        |
-    {set}       set set_option set_option_mode                               |
-    {su}        su resource [user]:identifier [password]:identifier          ;
-
-  base_clause =
-    base resource;
-
-  threshold_clause =
-    {float}   threshold float  |
-    {integer} threshold number ;
-
-  query =
-    select_clause from_clause? where_clause having_clause?
-    order_clause? limit_clause? offset_clause?;
-
-  triple_factor =
-    {unbraced} set_of_triples           |
-    {braced}   lpar set_of_triples rpar ;
-
-  set_of_triples =
-    {triple}   triple+                   |
-    {resource} resource                  |
-    {select}   select [subject]:element [predicate]:element [object]:element
-               from_clause? where_clause having_clause?
-               order_clause? limit_clause? offset_clause?;
-
-  triple =
-    [subject]:triple_element [predicate]:triple_element [object]:triple_element ;
-
-  triple_element =
-    {resource} resource |
-    {literal}  literal  |
-    {variable} variable ;
-
-  command_prefix =
-    {empty}               |
-    {alias} alias         |
-    {backup} backup       |
-    {commit} commit       |
-    {create} create       |
-    {delete} delete       |
-    {directory} directory |
-    {drop} drop           |
-    {execute} execute     |
-    {export} export       |
-    {help} help           |
-    {insert} insert       |
-    {load} load           |
-    {quit} quit           |
-    {restore} restore     |
-    {rollback} rollback   |
-    {apply} apply         |
-    {select} select       |
-    {set} set             |
-    {su} su               ;
-
-  set_option =
-    {autocommit} autocommit   |
-    {echo} echo               |
-    {statistics} statistics   |
-    {stoponerror} stoponerror |
-    {time} time               ;
-
-  set_option_mode =
-    {off} off |
-    {on} on   ;
-
-  select_clause =
-    {empty_select} select |
-    {normal_select} select element+;
-
-  from_clause =
-    from model_expression;
-
-  model_expression =
-    {term} model_term                     |
-    {or}   model_expression or model_term ;
-
-  model_term =
-    {part}   model_part                |
-    {and}    model_term and model_part ;
-
-  model_part =
-    {factor} model_factor                |
-    {xor}    model_part xor model_factor ;
-
-  model_factor =
-    {resource} resource                     |
-    {expression} lpar model_expression rpar ;
-
-  where_clause =
-    where constraint_expression;
-
-  having_clause =
-    having constraint_expression;
-
-  constraint =
-    [subject]:element [predicate]:element [object]:element in_clause? ;
-
-  in_clause =
-    in element ;
-
-  constraint_expression =
-    {term} constraint_term                          |
-    {or}   constraint_expression or constraint_term ;
-
-  constraint_term =
-    {dterm}  constraint_dterm                     |
-    {and}    constraint_term and constraint_dterm ;
-
-  constraint_dterm =
-    {factor} constraint_factor |
-    {minus} [minuend]:constraint_dterm minus [subtrahend]:constraint_factor ;
-
-  constraint_factor =
-    {constraint} exclude? constraint                  |
-    {compound} lbrace [subject]:element exists_expression in_clause? rbrace |
-    {existential} lbracket exists_expression in_clause? rbracket |
-    {expression} exclude? lpar constraint_expression rpar |
-    {transitive} transitive_clause |
-    {walk} walk_clause ;
-
-  exists_expression =
-    {eterm} exists_pterm  |
-    {colon} exists_expression colon exists_pterm ;
-
-  exists_pterm =
-    {pterm} [predicate]:element exists_oterm ;
-
-  exists_oterm =
-    {eo1} oterm |
-    {eo2} exists_oterm comma oterm ;
-
-  oterm = 
-    {oterm} [object]:element ;
-
-  transitive_clause =
-    {transitive1} trans lpar constraint rpar |
-    {transitive2} trans lpar [constraint1]:constraint and [constraint2]:constraint rpar ;
-
-  walk_clause =
-    {walk1} walk lpar [constraint1]:constraint and [constraint2]:constraint rpar;
-
-  order_clause =
-    order by order_element+ ;
-
-  order_element =
-    variable direction ;
-
-  direction =
-    {ascending}  asc? |
-    {descending} desc ;
-
-  limit_clause =
-    limit number;
-
-  offset_clause =
-    offset number;
-
-  element =
-    {variable}  variable                  |
-    {resource}  resource                  |
-    {literal}   literal                   |
-    {aggregate} aggregate lpar query rpar ;
-
-  aggregate =
-    {count}    count    |
-    {subquery} subquery ;
-
-  literal =
-    [opening]:quote strand* [closing]:quote language? datatype?;
-
-  strand =
-    {unescaped} text |
-    {escaped}   escapedtext;
-
-  datatype =
-    datatypeprefix resource;
-
-  language =
-    languageprefix langid;
-
-  variable =
-    variableprefix identifier;
-
-  locality =
-    {local} local |
-    {remote} remote ;
-

Copied: trunk/src/jar/querylang/sablecc/itql.grammar (from rev 1207, branches/mgr-143/src/jar/querylang/sablecc/itql.grammar)
===================================================================
--- trunk/src/jar/querylang/sablecc/itql.grammar	                        (rev 0)
+++ trunk/src/jar/querylang/sablecc/itql.grammar	2008-08-30 07:33:19 UTC (rev 1208)
@@ -0,0 +1,329 @@
+Package org.mulgara.itql;
+
+/*
+ * iTQL (SableCC grammar)
+ */
+
+Helpers
+  character  = [0..0xFFFF];
+  letter     = ['a'..'z'] | ['A'..'Z'];
+  digit      = ['0'..'9'];
+  tab        = 9;
+  lf         = 10;
+  cr         = 13;
+  sl         = 47;
+  whitespace = ' ' | tab | lf | cr;
+  nonblank   = [33..126];
+  nonquote   = [character - [39 + '\']];
+  nonslash   = [[33..126] - sl];
+  urlchar    = [character - '>'];
+
+States
+  def,  /* default state */
+  com,  /* comment */
+  esc,  /* escaping character in quoted literal with '\' */
+  lit,  /* quoted literal */
+  begres,  /* start of tagged resource */
+  endres,  /* end of tagged resource */
+  var,  /* escaping variable name with '$' */
+  lng;  /* language code */
+
+Tokens
+  {def}                alias       = 'alias';
+  {def}                and         = 'and';
+  {def}                apply       = 'apply';
+  {def}                as          = 'as';
+  {def}                asc         = 'asc';
+  {def}                autocommit  = 'autocommit';
+  {def}                backup      = 'backup';
+  {def}                base        = 'base';
+  {def}                by          = 'by';
+  {def}                commit      = 'commit';
+  {def}                count       = 'count';
+  {def}                create      = 'create';
+  {def}                delete      = 'delete';
+  {def}                desc        = 'desc';
+  {def}                directory   = 'directory';
+  {def}                drop        = 'drop';
+  {def}                echo        = 'echo';
+  {def}                execute     = 'execute';
+  {def}                exclude     = 'exclude';
+  {def}                export      = 'export';
+  {def}                from        = 'from';
+  {def}                help        = 'help';
+  {def}                in          = 'in';
+  {def}                insert      = 'insert';
+  {def}                into        = 'into';
+  {def}                limit       = 'limit';
+  {def}                load        = 'load';
+  {def}                minus       = 'minus';
+  {def}                off         = 'off';
+  {def}                offset      = 'offset';
+  {def}                or          = 'or';
+  {def}                order       = 'order';
+  {def}                on          = 'on';
+  {def}                quit        = 'quit';
+  {def}                restore     = 'restore';
+  {def}                rollback    = 'rollback';
+  {def}                select      = 'select';
+  {def}                set         = 'set';
+  {def}                statistics  = 'statistics';
+  {def}                stoponerror = 'stoponerror';
+  {def}                su          = 'su';
+  {def}                subquery    = 'subquery';
+  {def}                threshold   = 'threshold';
+  {def}                time        = 'time';
+  {def}                to          = 'to';
+  {def}                trans       = 'trans';
+  {def}                walk        = 'walk';
+  {def}                where       = 'where';
+  {def}                having      = 'having';
+  {def}                xor         = 'xor';
+  {def}                local       = 'local';
+  {def}                remote      = 'remote';
+
+
+  {def, var->def}      identifier = letter (letter | digit | '_' | '$' )*;
+  {def}                blank      = whitespace+;
+  {def->com}           hash        = '#';
+  {com}                comment    = [character - [lf + cr]];
+  {com->def}           endcomment = (lf | cr)+;
+  {def}                terminator = ';';
+  {def}                lpar       = '(';
+  {def}                rpar       = ')';
+  {def->begres}        url        = '<';
+  {endres->def}        endurl     = '>';
+  {def}                datatypeprefix = '^^';
+  {def->lng}           languageprefix = '@';
+  {def->var}           variableprefix = ('$' | '?');
+  {def}                number     = digit+;
+  {def}                float      = digit+ ('.' digit*) | ('.' digit+);
+  {lng->def}           langid      = letter letter | letter letter '-' letter letter;
+
+  {begres->endres}     resource    = urlchar*;
+  {def->lit, lit->def} quote       = 39;  /* ' */
+  {lit->esc}           escape      = '\';
+  {esc->lit}           escapedtext = character;
+  {lit}                text        = nonquote+;
+
+  {def}                lbrace     = '{';
+  {def}                rbrace     = '}';
+  {def}                lbracket   = '[';
+  {def}                rbracket   = ']';
+  {def}                colon      = ':';
+  {def}                comma      = ',';
+
+Ignored Tokens
+  blank, comment, escape, endcomment, endurl, hash, url;
+
+Productions
+  start =
+    {command} command? ;
+
+  command =
+    {alias}     alias [target]:resource as [prefix]:identifier               |
+    {aliasl}    alias                                                        |
+    {apply}     apply [rules]:resource to [base]:resource [destination]:resource? |
+    {backup}    backup [source]:resource to [locality]:locality? [destination]:resource |
+    {commit}    commit                                                       |
+    {create}    create [model]:resource [model_type]:resource?               |
+    {delete}    delete triple_factor from resource                           |
+    {directory} directory resource                                           |
+    {drop}      drop resource                                                |
+    {execute}   execute resource                                             |
+    {export}    export [source]:resource to [locality]:locality? [destination]:resource |
+    {help}      help command_prefix                                          |
+    {insert}    insert triple_factor into resource                           |
+    {load}      load [locality]:locality? [source]:resource into [destination]:resource |
+    {quit}      quit                                                         |
+    {restore}   restore [destination]:resource from [locality]:locality? [source]:resource |
+    {rollback}  rollback                                                     |
+    {select}    query                                                        |
+    {set}       set set_option set_option_mode                               |
+    {su}        su resource [user]:identifier [password]:identifier          ;
+
+  base_clause =
+    base resource;
+
+  threshold_clause =
+    {float}   threshold float  |
+    {integer} threshold number ;
+
+  query =
+    select_clause from_clause? where_clause having_clause?
+    order_clause? limit_clause? offset_clause?;
+
+  triple_factor =
+    {unbraced} set_of_triples           |
+    {braced}   lpar set_of_triples rpar ;
+
+  set_of_triples =
+    {triple}   triple+                   |
+    {resource} resource                  |
+    {select}   select [subject]:element [predicate]:element [object]:element
+               from_clause? where_clause having_clause?
+               order_clause? limit_clause? offset_clause?;
+
+  triple =
+    [subject]:triple_element [predicate]:triple_element [object]:triple_element ;
+
+  triple_element =
+    {resource} resource |
+    {literal}  literal  |
+    {variable} variable ;
+
+  command_prefix =
+    {empty}               |
+    {alias} alias         |
+    {backup} backup       |
+    {commit} commit       |
+    {create} create       |
+    {delete} delete       |
+    {directory} directory |
+    {drop} drop           |
+    {execute} execute     |
+    {export} export       |
+    {help} help           |
+    {insert} insert       |
+    {load} load           |
+    {quit} quit           |
+    {restore} restore     |
+    {rollback} rollback   |
+    {apply} apply         |
+    {select} select       |
+    {set} set             |
+    {su} su               ;
+
+  set_option =
+    {autocommit} autocommit   |
+    {echo} echo               |
+    {statistics} statistics   |
+    {stoponerror} stoponerror |
+    {time} time               ;
+
+  set_option_mode =
+    {off} off |
+    {on} on   ;
+
+  select_clause =
+    {empty_select} select |
+    {normal_select} select element+;
+
+  from_clause =
+    from model_expression;
+
+  model_expression =
+    {term} model_term                     |
+    {or}   model_expression or model_term ;
+
+  model_term =
+    {part}   model_part                |
+    {and}    model_term and model_part ;
+
+  model_part =
+    {factor} model_factor                |
+    {xor}    model_part xor model_factor ;
+
+  model_factor =
+    {resource} resource                     |
+    {expression} lpar model_expression rpar ;
+
+  where_clause =
+    where constraint_expression;
+
+  having_clause =
+    having constraint_expression;
+
+  constraint =
+    [subject]:element [predicate]:element [object]:element in_clause? ;
+
+  in_clause =
+    in element ;
+
+  constraint_expression =
+    {term} constraint_term                          |
+    {or}   constraint_expression or constraint_term ;
+
+  constraint_term =
+    {dterm}  constraint_dterm                     |
+    {and}    constraint_term and constraint_dterm ;
+
+  constraint_dterm =
+    {factor} constraint_factor |
+    {minus} [minuend]:constraint_dterm minus [subtrahend]:constraint_factor ;
+
+  constraint_factor =
+    {constraint} exclude? constraint                  |
+    {compound} lbrace [subject]:element exists_expression in_clause? rbrace |
+    {existential} lbracket exists_expression in_clause? rbracket |
+    {expression} exclude? lpar constraint_expression rpar |
+    {transitive} transitive_clause |
+    {walk} walk_clause ;
+
+  exists_expression =
+    {eterm} exists_pterm  |
+    {colon} exists_expression colon exists_pterm ;
+
+  exists_pterm =
+    {pterm} [predicate]:element exists_oterm ;
+
+  exists_oterm =
+    {eo1} oterm |
+    {eo2} exists_oterm comma oterm ;
+
+  oterm = 
+    {oterm} [object]:element ;
+
+  transitive_clause =
+    {transitive1} trans lpar constraint rpar |
+    {transitive2} trans lpar [constraint1]:constraint and [constraint2]:constraint rpar ;
+
+  walk_clause =
+    {walk1} walk lpar [constraint1]:constraint and [constraint2]:constraint rpar;
+
+  order_clause =
+    order by order_element+ ;
+
+  order_element =
+    variable direction ;
+
+  direction =
+    {ascending}  asc? |
+    {descending} desc ;
+
+  limit_clause =
+    limit number;
+
+  offset_clause =
+    offset number;
+
+  element =
+    {variable}  variable                  |
+    {resource}  resource                  |
+    {literal}   literal                   |
+    {aggregate} aggregate lpar query rpar ;
+
+  aggregate =
+    {count}    count    |
+    {subquery} subquery ;
+
+  literal =
+    [opening]:quote strand* [closing]:quote language? datatype?;
+
+  strand =
+    {unescaped} text |
+    {escaped}   escapedtext;
+
+  datatype =
+    datatypeprefix resource;
+
+  language =
+    languageprefix langid;
+
+  variable =
+    variableprefix identifier;
+
+  locality =
+    {local} local |
+    {remote} remote ;
+

Modified: trunk/src/jar/server-beep/build.xml
===================================================================
--- trunk/src/jar/server-beep/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/server-beep/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -24,7 +24,7 @@
     <fileset file="${query.dist.dir}/${query.jar}"/>
     <fileset file="${server.dist.dir}/${server.jar}"/>
     <fileset file="${sparql-protocol.dist.dir}/${sparql-protocol.jar}"/>
-    <fileset file="${itql.dist.dir}/${itql.jar}"/>
+    <fileset file="${querylang.dist.dir}/${querylang.jar}"/>
     <fileset file="${util.dist.dir}/${util.jar}"/>
     <fileset file="${rules.dist.dir}/${rules.jar}"/>
 
@@ -60,7 +60,7 @@
   </target>
 
   <target name="server-beep-compile"
-          depends="-server-beep-prepare, itql-jar, query-jar, server-jar, rules-jar,
+          depends="-server-beep-prepare, querylang-jar, query-jar, server-jar, rules-jar,
                    sparql-protocol-jar"
           description="Compiles all server-beep related files included generated
                        source code">

Modified: trunk/src/jar/server-http/build.xml
===================================================================
--- trunk/src/jar/server-http/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/server-http/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -23,7 +23,7 @@
 
     <fileset file="${query.dist.dir}/${query.jar}"/>
     <fileset file="${server.dist.dir}/${server.jar}"/>
-    <fileset file="${itql.dist.dir}/${itql.jar}"/>
+    <fileset file="${querylang.dist.dir}/${querylang.jar}"/>
     <fileset file="${rules.dist.dir}/${rules.jar}"/>
     <fileset file="${lib.dir}/javax.servlet-2.3.jar"/>
   </path>
@@ -59,7 +59,7 @@
   </target>
 
   <target name="server-http-compile"
-          depends="-server-http-prepare, itql-jar, server-jar"
+          depends="-server-http-prepare, querylang-jar, server-jar"
           description="Compiles all server-http related files included generated
                        source code">
 
@@ -91,7 +91,7 @@
   </target>
 
   <target name="server-http-war-compile"
-          depends="-server-http-prepare, query-jar, itql-jar, server-jar,
+          depends="-server-http-prepare, query-jar, querylang-jar, server-jar,
                    util-jar"
           description="Compiles all server-http war related files including
                        generated source code">
@@ -118,7 +118,7 @@
       <classes dir="${server-http.war.obj.dir}/classes"/>
 
       <lib dir="${server-http.war.dist.dir}" includes="${query.jar},
-                                                       ${itql.jar},
+                                                       ${querylang.jar},
                                                        ${util.jar},
                                                        ${rules.jar}"/>
     </war>
@@ -133,7 +133,7 @@
   </target>
 
   <target name="server-http-dist"
-          depends="query-jar, driver-jar, itql-jar, util-jar, config-jar,
+          depends="query-jar, driver-jar, querylang-jar, util-jar, config-jar,
                    dtd-compile, server-jar, server-http-war, javadoc-dist,
                    webui-war"
           description="Performs all tasks related to finalising this server-http
@@ -150,7 +150,7 @@
     <manifest file="${obj.dir}/META-INF/MANIFEST_Mulgara_HTTP_BOOTSTRAP.MF">
 
       <attribute name="Main-Class" value="org.mulgara.util.Bootstrap"/>
-      <attribute name="Embedded-Jar" value="lib/${driver.jar}, lib/${query.jar},lib/${itql.jar}, lib/${rules.jar}, lib/${server.jar}, lib/${util.jar}, lib/${config.jar}, lib/activation-1.0.2.jar, lib/icu4j.jar, lib/jena-2.1.jar,lib/antlr.jar, lib/${commons-logging.jar}, lib/log4j-1.2.15.jar, lib/mail-1.3.jar, lib/${jetty.jar},lib/${jetty.plus.jar}, lib/${jasper.runtime.jar}, lib/${servlet.jar}, lib/jargs-0.2.jar,lib/${castor-xml.jar}, lib/${castor-xml-schema.jar}, lib/xercesImpl.jar, lib/xmlParserAPIs.jar, lib/${jrdf.jar},lib/jakarta-oro-2.0.5.jar, lib/${emory-util.jar}, lib/${sesame-model.jar}"/>
+      <attribute name="Embedded-Jar" value="lib/${driver.jar}, lib/${query.jar},lib/${querylang.jar}, lib/${rules.jar}, lib/${server.jar}, lib/${util.jar}, lib/${config.jar}, lib/activation-1.0.2.jar, lib/icu4j.jar, lib/jena-2.1.jar,lib/antlr.jar, lib/${commons-logging.jar}, lib/log4j-1.2.15.jar, lib/mail-1.3.jar, lib/${jetty.jar},lib/${jetty.plus.jar}, lib/${jasper.runtime.jar}, lib/${servlet.jar}, lib/jargs-0.2.jar,lib/${castor-xml.jar}, lib/${castor-xml-schema.jar}, lib/xercesImpl.jar, lib/xmlParserAPIs.jar, lib/${jrdf.jar},lib/jakarta-oro-2.0.5.jar, lib/${emory-util.jar}, lib/${sesame-model.jar}"/>
       <attribute name="Embedded-Main-Class" value="org.mulgara.server.EmbeddedMulgaraHttpServer"/>
     </manifest>
 
@@ -177,7 +177,7 @@
           ${jetty.jar}, ${jetty.plus.jar}, ${servlet.jar}, ${jasper.runtime.jar},
           xerces*.jar, mail-*.jar, castor*.jar, trove-*.jar, ${jrdf.jar}, ${emory-util.jar}, ${sesame-model.jar}"/>
       <zipfileset dir="${bin.dir}" prefix="lib" includes="${query.jar},
-          ${driver.jar}, ${itql.jar}, ${server.jar},
+          ${driver.jar}, ${querylang.jar}, ${server.jar},
           ${util.jar}, ${config.jar}"/>
       <zipfileset dir="${basedir}/data" prefix="data" includes="**/*.rdfs"/>
 
@@ -209,7 +209,7 @@
       <srcfiles dir="${bin.dir}" includes="${server-http.jar}"/>
       <srcfiles dir="${bin.dir}" includes="${driver.jar}"/>
       <srcfiles dir="${bin.dir}" includes="${query.jar}"/>
-      <srcfiles dir="${bin.dir}" includes="${itql.jar}"/>
+      <srcfiles dir="${bin.dir}" includes="${querylang.jar}"/>
       <srcfiles dir="${bin.dir}" includes="${server.jar}"/>
       <srcfiles dir="${bin.dir}" includes="${util.jar}"/>
       <srcfiles dir="${bin.dir}" includes="${config.jar}"/>

Modified: trunk/src/jar/server-local/build.xml
===================================================================
--- trunk/src/jar/server-local/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/server-local/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -23,7 +23,7 @@
 
     <fileset file="${driver.dist.dir}/${driver.jar}"/>
     <fileset file="${query.dist.dir}/${query.jar}"/>
-    <fileset file="${itql.dist.dir}/${itql.jar}"/>
+    <fileset file="${querylang.dist.dir}/${querylang.jar}"/>
     <fileset file="${util.dist.dir}/${util.jar}"/>
   </path>
 
@@ -58,7 +58,7 @@
   </target>
 
   <target name="server-local-compile"
-          depends="-server-local-prepare, itql-jar, server-jar"
+          depends="-server-local-prepare, querylang-jar, server-jar"
           description="Compiles all server-local related files included
                        generated source code"
           unless="server-local.classes.uptodate">

Modified: trunk/src/jar/sofa/build.xml
===================================================================
--- trunk/src/jar/sofa/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/sofa/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -28,7 +28,7 @@
     <pathelement path="${client-jrdf.dist.dir}/${client-jrdf.jar}"/>
     <pathelement path="${server-rmi.dist.dir}/${server-rmi.jar}"/>
     <pathelement path="${resolver-spi.dist.dir}/${resolver-spi.jar}"/>
-    <pathelement path="${itql.dist.dir}/${itql.jar}"/>
+    <pathelement path="${querylang.dist.dir}/${querylang.jar}"/>
     <pathelement path="${lib.dir}/${jrdf.jar}"/>
     <pathelement path="${lib.dir}/${sesame-model.jar}"/>
     <pathelement path="${lib.dir}/${sofa.jar}"/>
@@ -66,7 +66,7 @@
   </target>
 
   <target name="sofa-compile"
-          depends="-sofa-prepare, driver-jar, itql-jar, server-jar, jrdf-jar,
+          depends="-sofa-prepare, driver-jar, querylang-jar, server-jar, jrdf-jar,
           client-jrdf-jar, resolver-spi-jar"
           description="Compiles all sofa related files included generated
                        source code">

Modified: trunk/src/jar/sparql-protocol/build.xml
===================================================================
--- trunk/src/jar/sparql-protocol/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/sparql-protocol/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -23,7 +23,7 @@
 
     <fileset file="${query.dist.dir}/${query.jar}"/>
     <fileset file="${server.dist.dir}/${server.jar}"/>
-    <fileset file="${itql.dist.dir}/${itql.jar}"/>
+    <fileset file="${querylang.dist.dir}/${querylang.jar}"/>
     <fileset file="${util.dist.dir}/${util.jar}"/>
 
     <fileset dir="${lib.dir}" includes="jsr173_07_api.jar, jsr173_07_ri.jar"/>
@@ -58,7 +58,7 @@
   </target>
 
   <target name="sparql-protocol-compile"
-          depends="-sparql-protocol-prepare, server-jar, itql-jar"
+          depends="-sparql-protocol-prepare, server-jar, querylang-jar"
           description="Compiles all sparql-protocol related files included generated
                        source code">
 

Modified: trunk/src/jar/web/build.xml
===================================================================
--- trunk/src/jar/web/build.xml	2008-08-30 03:09:43 UTC (rev 1207)
+++ trunk/src/jar/web/build.xml	2008-08-30 07:33:19 UTC (rev 1208)
@@ -21,7 +21,7 @@
     <path refid="common-classpath"/>
     <fileset file="${util.dist.dir}/${util.jar}"/>
     <fileset file="${query.dist.dir}/${query.jar}"/>
-    <fileset file="${itql.dist.dir}/${itql.jar}"/>
+    <fileset file="${querylang.dist.dir}/${querylang.jar}"/>
     <fileset file="${server.dist.dir}/${server.jar}"/>
     <fileset file="${lib.dir}/${jetty.jar}"/>
     <fileset file="${lib.dir}/${jetty-plus.jar}"/>
@@ -63,7 +63,7 @@
   </target>
 
   <target name="web-compile"
-          depends="-web-prepare, util-jar, config-jar, itql-jar, query-jar, -web-unjar-config"
+          depends="-web-prepare, util-jar, config-jar, querylang-jar, query-jar, -web-unjar-config"
           description="Compiles all web related files included generated
                        source code"
           unless="web.classes.uptodate">




More information about the Mulgara-svn mailing list