[Mulgara-svn] r495 - in branches/nw-interface/src/jar: client-jrdf/java/org/mulgara/client/jrdf/util itql/java/org/mulgara/itql krule/java/org/mulgara/krule
pag at mulgara.org
pag at mulgara.org
Wed Oct 24 15:03:09 UTC 2007
Author: pag
Date: 2007-10-24 10:03:08 -0500 (Wed, 24 Oct 2007)
New Revision: 495
Removed:
branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java
branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java
Modified:
branches/nw-interface/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java
branches/nw-interface/src/jar/krule/java/org/mulgara/krule/KruleLoader.java
branches/nw-interface/src/jar/krule/java/org/mulgara/krule/QueryStruct.java
branches/nw-interface/src/jar/krule/java/org/mulgara/krule/RuleStructure.java
Log:
Removed ItqlInterpreter. This was removed to prove that the deprecated interfaces are no longer in use. This resulted in updates to some client-jrdf code and Krule code. While there, I added generics to the Krule code.
Modified: branches/nw-interface/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java
===================================================================
--- branches/nw-interface/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java 2007-10-23 03:33:36 UTC (rev 494)
+++ branches/nw-interface/src/jar/client-jrdf/java/org/mulgara/client/jrdf/util/ItqlQueryUtil.java 2007-10-24 15:03:08 UTC (rev 495)
@@ -111,7 +111,7 @@
* @throws GraphException
* @return Answer
*/
- public static Answer executeQuery(String query, ItqlInterpreter interpreter,
+ public static Answer executeQuery(String query, TqlInterpreter interpreter,
Session session) throws GraphException {
try {
@@ -149,7 +149,7 @@
* @param session Session
* @throws GraphException
*/
- public static void executeCommand(String command, ItqlInterpreter interpreter,
+ public static void executeCommand(String command, TqlInterpreter interpreter,
Session session) throws GraphException {
Answer answer = null;
Deleted: branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java
===================================================================
--- branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java 2007-10-23 03:33:36 UTC (rev 494)
+++ branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreter.java 2007-10-24 15:03:08 UTC (rev 495)
@@ -1,3837 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public License
- * Version 1.1 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- *
- * The Original Code is the Kowari Metadata Store.
- *
- * The Initial Developer of the Original Code is Plugged In Software Pty
- * Ltd (http://www.pisoftware.com, mailto:info at pisoftware.com). Portions
- * created by Plugged In Software Pty Ltd are Copyright (C) 2001,2002
- * Plugged In Software Pty Ltd. All Rights Reserved.
- *
- * Contributor(s):
- * Copywrite in the anon-variable support:
- * The Australian Commonwealth Government
- * Department of Defense
- * Developed by Netymon Pty Ltd
- * under contract 4500507038
- * contributed to the Mulgara Project under the
- * Mozilla Public License version 1.1
- * per clause 4.1.3 and 4.1.4 of the above contract.
- *
- * [NOTE: The text of this Exhibit A may differ slightly from the text
- * of the notices in the Source Code files of the Original Code. You
- * should use the text of this Exhibit A rather than the text found in the
- * Original Code Source Code for Your Modifications.]
- *
- */
-
-package org.mulgara.itql;
-
-// Java 2 standard packages
-import java.io.*;
-import java.net.*;
-import java.util.*;
-import java.rmi.server.UnicastRemoteObject;
-import java.rmi.RemoteException;
-import java.rmi.NoSuchObjectException;
-
-// Third party packages
-
-import org.apache.log4j.Logger; // Apache Log4J
-import org.jrdf.graph.*; // JRDF
-
-// Locally written packages
-
-// Automatically generated packages (SableCC)
-import org.mulgara.itql.analysis.*;
-import org.mulgara.itql.lexer.*;
-import org.mulgara.itql.node.*;
-import org.mulgara.itql.parser.*;
-import org.mulgara.query.operation.Command;
-import org.mulgara.parser.MulgaraLexerException;
-import org.mulgara.parser.MulgaraParserException;
-import org.mulgara.query.*;
-import org.mulgara.query.rdf.*;
-import org.mulgara.rules.*;
-import org.mulgara.server.NonRemoteSessionException;
-import org.mulgara.server.Session;
-import org.mulgara.server.SessionFactory;
-import org.mulgara.server.driver.SessionFactoryFinder;
-import org.mulgara.server.driver.SessionFactoryFinderException;
-
-// emory util package
-import edu.emory.mathcs.util.remote.io.*;
-import edu.emory.mathcs.util.remote.io.server.impl.*;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.ZipInputStream;
-
-/**
- * Interactive TQL (ITQL) command interpreter.
- * <p>
- * Responsible for the following :
- * - maintains connectivty between client and server;
- * - parsing and converting TQL requests to query objects for execution;
- * - Abstract layer for the {@link ItqlInterpreterBean} and {@link org.mulgara.connection.MulgaraConnection}s.
- * </p>
- *
- * @created 2001-08-21
- * @author Simon Raboczi
- * @author Tom Adams
- * @author Paul Gearon
- * @company <a href="mailto:info at PIsoftware.com">Plugged In Software</a>
- * @copyright ©2001-2004 <a href="http://www.tucanatech.com/">Tucana Technologies, Inc.</a>
- * @copyright ©2005 <a href="mailto:pgearon at users.sourceforge.net">Paul Gearon</a>
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlInterpreter extends DepthFirstAdapter implements SableCCInterpreter, Aliasing {
-
- /**
- * Get line separator.
- */
- private static final String EOL = System.getProperty("line.separator");
-
- /**
- * the logger
- */
- private static final Logger logger =
- Logger.getLogger(ItqlInterpreter.class.getName());
-
- /**
- * the message to display to the user if no results message was specififed by
- * a command
- */
- private final static String DEFAULT_RESULT_MESSAGE = "No results";
-
- /**
- * A constraint expression builder.
- */
- private ConstraintExpressionBuilder builder = new ConstraintExpressionBuilder(this);
-
- /**
- * Variable factory for this interpreter.
- */
- private VariableFactory variableFactory = new VariableFactoryImpl();
-
- /**
- * Lexer...
- */
- Lexer2 lexer = new Lexer2();
-
- //
- // Members
- //
-
- /**
- * the driver used to communicate with the database
- */
- private Session session = null;
-
- /**
- * A session provided by an external source. Also acts as a flag to indicate that
- * a session has been provided.
- */
- private Session providedSession = null;
-
- /**
- * the map from targets to aliases
- */
- private Map aliasMap = null;
-
- /**
- * a flag indicating the user has entered the quit command
- */
- private boolean quitRequested = false;
-
- /**
- * the last query parsed
- */
- private Query lastQuery = null;
-
- /**
- * the query should be executed when it has been parsed
- */
- private boolean executeQuery = true;
-
- /**
- * the results of the last command execution
- */
- private Answer lastAnswer = null;
-
- /**
- * the results of the last command execution
- */
- private String lastMessage = null;
-
- /**
- * the results of the last error
- */
- private ItqlInterpreterException lastError = null;
-
- /**
- * the time a command started
- */
- private long commandStartTime = -1L;
-
- /**
- * the log file to record all iTQL requests *
- */
- private PrintWriter itqlLog = null;
-
- /**
- * the location of the log iTQL file
- */
- private String itqlLogFile = null;
-
- /**
- * Map from security domain URIs to {@link Login} records.
- */
- private final Map loginMap = new HashMap();
-
- /**
- * The URI of the server of the current {@link #session}.
- */
- private URI serverURI = null;
-
- /**
- * The security domain for the session factory that produced
- * {@link #session}.
- */
- private URI securityDomainURI = null;
-
- /**
- * This will be <code>true</code> if {@link #autoCommit} is
- * <code>false</code> and the {@link #session} has been {@link #update}d.
- */
- private boolean transactionUpdated = false;
-
- /**
- * True if we are using a local session.
- */
- public boolean isLocal;
-
- //
- // Interpreter options
- //
-
- /**
- * the option to automatically make each method call transactional
- */
- private boolean autoCommit = true;
-
- /**
- * the option to enable the echoing of command output
- */
- private boolean echoOption = true;
-
- /**
- * the option to enable the display of command statistics
- */
- private boolean statisticsOption = false;
-
- /**
- * the option to enable the stopping of the interpreter on error in scripts
- */
- private boolean stoponerrorOption = false;
-
- /**
- * the option to enable the timing of commands
- */
- private boolean timeOption = false;
-
- /**
- * The next anonymous variable suffix
- */
- private int anonSuffix = 0;
-
- //
- // Constructors
- //
-
- /**
- * Creates a new ITQL command interpreter.
- *
- * @param aliasMap the map from targets to aliases, never <code>null</code>
- */
- public ItqlInterpreter(Map aliasMap) {
-
- // validate aliasMap parameter
- if (aliasMap == null) {
- throw new IllegalArgumentException("Null \"alias\" parameter");
- }
-
- // set members
- this.setAliasMap(aliasMap);
- this.setQuitRequested(false);
-
- // log the creation of this interpreter
- if (logger.isDebugEnabled()) {
- logger.debug("Itql interpreter created");
- }
-
- // is this session configured for logging.
- if (System.getProperty("itql.command.log") != null) {
- itqlLogFile = System.getProperty("itql.command.log");
- logger.info("iTQL command logging has been enabled. Logging to " + System.getProperty("itql.command.log"));
- }
- }
-
- /**
- * Constructor internal to Mulgara that accepts a provided session.
- *
- * @param providedSession The session to use.
- * @param aliasMap the map from targets to aliases, never <code>null</code>
- */
- public ItqlInterpreter(Session providedSession, Map aliasMap) {
- this(aliasMap);
- // validate providedSession parameter
- if (providedSession == null) {
- throw new IllegalArgumentException("Null session parameter");
- }
-
- this.providedSession = providedSession;
- this.session = providedSession;
- }
-
-
- /**
- * Set up default aliases.
- *
- * @return A map of aliases to their fully qualified names
- */
- public static Map getDefaultAliases() {
- Map aliases = new HashMap();
- try {
- aliases.put(RDF, new URI(RDF_NS));
- aliases.put(RDFS, new URI(RDFS_NS));
- aliases.put(OWL, new URI(OWL_NS));
- aliases.put(MULGARA, new URI(MULGARA_NS));
- aliases.put(KRULE, new URI(KRULE_NS));
- } catch (URISyntaxException e) {
- /* get those aliases which we could */
- logger.error("Error defining internal aliases: ", e);
- }
- return aliases;
- }
-
-
- /**
- * @return whether there are unparsed tokens from an unterminated command
- */
- public boolean isComplete() {
-
- return lexer.leftoverTokenList.size() == 0;
- }
-
- /**
- * Returns true if a quit command has been entered. <p>
- *
- * Note. This method will return true after a quit command has been issued. It
- * is up to the user of this class to check for a quit after each command has
- * been issued, eg. </p> <pre>
- * while (!interpreter.isQuitRequested()) {
- * String result = interpreter.executeCommand(command);
- * }
- * </pre>
- *
- * @return true if a quit command has been entered
- */
- public boolean isQuitRequested() {
-
- return this.quitRequested;
- }
-
- // toNode()
-
- /**
- * Returns the error of the last query. Methods overriding {@link
- * org.mulgara.itql.analysis.DepthFirstAdapter} are expected to set a
- * results message, even if that message is null. The is for APIs, logging
- * and programmers not for users.
- *
- * @return the error of the last query, <code>null</code> if the query did not
- * fail
- * @see #setLastError(Exception)
- */
- public ItqlInterpreterException getLastError() {
-
- return this.lastError;
- }
-
- /**
- * Returns the results of the last query. Methods overriding {@link
- * org.mulgara.itql.analysis.DepthFirstAdapter} are expected to set a
- * results message, even if that message is null.
- *
- * @return the results of the last query, <code>null</code> if the query
- * failed
- * @see #setLastAnswer(Answer)
- */
- public Answer getLastAnswer() {
- return this.lastAnswer;
- }
-
- /**
- * Returns the results of the last command execution. Methods overriding
- * {@link org.mulgara.itql.analysis.DepthFirstAdapter} are expected to set
- * a results message, even if that message is null. This is the user
- * understandable message.
- *
- * @return the results of the last command execution, null if the command did
- * not set any message
- * @see #setLastMessage(String)
- */
- public String getLastMessage() {
-
- return this.lastMessage;
- }
-
- // ItqlInterpreter()
- //
- // Public API
- //
-
- /**
- * Executes the given ITQL command.
- *
- * @param command the command to execute in ITQL syntax
- * @throws 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 void executeCommand(String command) throws MulgaraParserException,
- LexerException, Exception {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // validate command parameter
- if ((command == null) || command.equals("")) {
- throw new IllegalArgumentException("Null \"command\" parameter");
- } // end if
-
- // log that we're going to execute the command
- if (logger.isDebugEnabled()) {
- logger.debug("Executing command " + command);
- }
-
- // log the iTQL command - system property itql.command.log must be set
- this.logItql(command);
-
- // Reset the variable incrementer in the query.
- variableFactory.reset();
-
- // push the command into the lexer
- lexer.add(command);
-
- // if the lexer saw terminators, parse the associated commands
- while (lexer.nextCommand()) {
-
- Start commandTree = null;
-
- // parse the command
- try {
- Parser parser = new Parser(lexer);
- commandTree = parser.parse();
- } catch (ParserException pe) {
-
- // let the user know the problem
- this.setLastError(pe);
- this.setLastAnswer(null);
- this.setLastMessage("Syntax error " + EOL + ItqlUtil.getCause(pe, 2));
- flush();
- throw new MulgaraParserException(pe);
- } catch (LexerException le) {
-
- // let the user know the problem
- this.setLastError(le);
- this.setLastAnswer(null);
- this.setLastMessage("Lexer exception " + EOL + ItqlUtil.getCause(le, 2));
- flush();
- throw le;
- }
-
- // execute the command
- try {
- commandTree.apply(this);
- } catch (Exception e) {
- flush();
- throw e;
- } catch (Error e) {
-
- flush();
- throw e;
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("Successfully executed command " + command);
- }
- }
- }
-
- /**
- * Discard any unparsed tokens.
- *
- */
- public void flush() {
-
- lexer.leftoverTokenList.clear();
- }
-
- // isQuitRequested()
-
- /**
- * Parses the given TQL command. This implementation only understands Query commands.
- *
- * @param command the command to parse in TQL syntax
- * @return An AST for the command
- * @throws MulgaraParserException if the syntax of the command is incorrect
- * @throws MulgaraLexerException if the syntax of the command is incorrect
- * @throws IOException if the <var>command</var> cannot be paersed
- * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
- */
- public Command parseCommand(String command) throws MulgaraParserException, MulgaraLexerException, IOException {
- return parseQuery(command);
- }
-
-
- /**
- * Parses the given TQL command.
- *
- * @param command the command to parse in TQL syntax
- * @return A {@link List} of ASTs, one for each command
- * @throws MulgaraParserException if the syntax of the command is incorrect
- * @throws MulgaraLexerException if the syntax of the command is incorrect
- * @throws IOException if the <var>command</var> cannot be paersed
- * @throws IllegalArgumentException if the <var>command</var> is <code>null</code>
- */
- public List<Command> parseCommands(String command) throws MulgaraParserException, MulgaraLexerException, IOException {
- throw new UnsupportedOperationException("Commands are not supported in this interface");
- }
-
-
- /**
- * Parse a string into a {@link Query}.
- *
- * @param queryString a string containing an ITQL query
- * @return the corresponding {@link Query} instance
- * @throws IOException if <var>queryString</var> can't be buffered.
- * @throws LexerException if <var>queryString</var> can't be tokenized.
- * @throws 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 + "\"");
- }
-
- // execute the command
- Parser parser = new Parser(new Lexer(new PushbackReader(new StringReader(queryString), 256)));
- lastQuery = null;
- try {
- executeQuery = false;
- parser.parse().apply(this);
- } catch (LexerException le) {
- throw new MulgaraLexerException(le);
- } catch (ParserException le) {
- throw new MulgaraParserException(le);
- } finally {
- executeQuery = true;
- }
-
- if (lastQuery == null) {
- throw new MulgaraParserException("Parameter was not a query");
- }
-
- // return the results of the command
- return lastQuery;
- }
-
-
- //
- // Methods overridden from DepthFirstAdapter
- //
-
- /**
- * Hijacks the start of every command to perform actions on interpreter
- * options.
- *
- * @param node a command to be executed by the interpreter
- */
- public void inACommandStart(ACommandStart node) {
-
- // set the time of the start of the command
- this.setCommandStartTime(System.currentTimeMillis());
- }
-
- // inACommandStart()
-
- /**
- * Load the contents of an InputStream into a database/model. The method assumes
- * the source to be RDF/XML.
- *
- * @param inputStream a locally supplied inputstream.
- * @param destinationURI destination model for the source data
- * @return number of rows inserted into the destination model
- * @throws QueryException if the data fails to load
- */
- public long load(InputStream inputStream, URI destinationURI)
- throws QueryException {
-
- if ( inputStream == null ) {
- throw new IllegalArgumentException("Null InputStream supplied");
- }
- if ( destinationURI == null ) {
- throw new IllegalArgumentException("Null destination URI supplied");
- }
-
- URI dummySourceURI = null;
- try {
-
- // create dummy URI to force the server to assume RDF/XML inputStream
- dummySourceURI = new URI(Mulgara.NAMESPACE+"locally-sourced-inputStream.rdf");
-
- } catch ( URISyntaxException ex ) {};
-
- return this.load(inputStream, dummySourceURI, destinationURI);
-
- }
-
- /**
- * Load the contents of an InputStream or a URI into a database/model.
- *
- * @param inputStream a locally supplied inputstream. Null assumes the
- * server will obtain the stream from the sourceURI.
- * @param sourceURI an idenifier for the source or inputstream. The extension
- * will determine the type of parser to be used. ie. .rdf or .n3 When an inputStream
- * is supplied the server will not attempt to read the contents of the sourceURI
- * @param destinationURI destination model for the source data
- * @return number of rows inserted into the destination model
- * @throws QueryException if the data fails to load
- */
- public long load(InputStream inputStream, URI sourceURI, URI destinationURI)
- throws QueryException {
-
- RemoteInputStreamSrvImpl srv = null;
-
- if ( sourceURI == null ) {
- throw new IllegalArgumentException("Null source URI supplied");
- }
- if ( destinationURI == null ) {
- throw new IllegalArgumentException("Null destination URI supplied");
- }
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Loading "+sourceURI+" into " +destinationURI );
- }
-
- long stmtCount = 0;
-
- // update the session
- this.updateSession(new ModelResource(destinationURI));
-
- if ( inputStream != null ) {
-
- //is the file/stream compressed?
- try {
- String path = (sourceURI == null) ? "" : sourceURI.toString();
- inputStream = adjustForCompression(path, inputStream);
- } catch (IOException ioException) {
-
- throw new QueryException("Could not get InputStream for compressed file.",
- ioException);
- }
-
- // open and wrap the inputstream
- srv = new RemoteInputStreamSrvImpl(inputStream);
-
- try {
-
- // prepare it for exporting
- UnicastRemoteObject.exportObject(srv);
-
- } catch ( RemoteException rex ) {
- throw new QueryException("Unable to create a remote InputStream to "+
- "load statements into "+ destinationURI, rex);
- }
-
- inputStream = new RemoteInputStream(srv);
- }
-
- try {
- stmtCount =
- this.getSession().setModel( inputStream,
- destinationURI, // model to redefine
- new ModelResource(sourceURI));
- } finally {
- if ( srv != null ) {
- try {
- UnicastRemoteObject.unexportObject(srv, false);
- } catch ( NoSuchObjectException ex ) {};
- }
- }
- update();
-
- // log that we've loaded the contents of the file
- if (logger.isDebugEnabled()) {
-
- logger.debug("Loaded " + stmtCount + " statements from " + sourceURI +
- " into " + destinationURI);
- }
-
- // tell the user
- if (stmtCount > 0L) {
-
- this.setLastMessage("Successfully loaded " + stmtCount +
- " statements from " + sourceURI + " into " +
- destinationURI);
- }
- else {
-
- this.setLastMessage("WARNING: No valid RDF statements found in " +
- sourceURI);
- } // end if
-
- return stmtCount;
-
- }
-
- /**
- * Backup all the data on the specified server or model to a local file.
- * The database is not changed by this method.
- *
- * @param sourceURI The URI of the server or model to backup.
- * @param destinationFile an non-existent file on the local file system to
- * receive the backup contents.
- * @throws QueryException if the backup cannot be completed.
- */
- public void backup(URI sourceURI, File destinationFile )
- throws QueryException {
-
- FileOutputStream fileOutputStream = null;
- try {
-
- fileOutputStream = new FileOutputStream(destinationFile);
- }
- catch (FileNotFoundException ex) {
- throw new QueryException("File "+destinationFile+" cannot be created "+
- "for backup. ", ex);
- }
-
- this.backup( sourceURI, fileOutputStream );
-
- // assume the server may not have closed the file.
- if ( fileOutputStream != null) {
- try {
- fileOutputStream .close();
- } catch (IOException ioe ) {};
- }
- }
-
- /**
- * Backup all the data on the specified server to an output stream.
- * The database is not changed by this method.
- *
- * @param sourceURI The URI of the server or model to backup.
- * @param outputStream The stream to receive the contents
- * @throws QueryException if the backup cannot be completed.
- */
- public void backup(URI sourceURI, OutputStream outputStream)
- throws QueryException {
-
- // open and wrap the outputstream
- RemoteOutputStreamSrvImpl srv = new RemoteOutputStreamSrvImpl(outputStream);
-
- // prepare it for exporting
- try {
- UnicastRemoteObject.exportObject(srv);
- }
- catch (RemoteException rex) {
- throw new QueryException("Unable to backup "+serverURI + " to "+
- "an output stream", rex);
- }
-
- outputStream = new RemoteOutputStream(srv);
-
- // set the server URI given a possible model
- this.setBackupServer( sourceURI );
-
- try {
- // perform the backup
- this.getSession().backup( sourceURI, outputStream );
-
- } finally {
- if ( outputStream != null) {
- try {
- outputStream.close();
- } catch (IOException ioe ) {};
- }
- if ( srv != null ) {
- try {
- UnicastRemoteObject.unexportObject(srv, false);
- } catch ( NoSuchObjectException ex ) {};
- }
- }
- if ( outputStream != null) {
- try {
- outputStream.close();
- } catch (IOException ioe ) {};
- }
- }
-
- /**
- * Restore all the data on the specified server. If the database is not
- * currently empty then the database will contain the union of its current
- * content and the content of the backup file when this method returns.
- *
- * @param inputStream A stream to obtain the restore from.
- * @param serverURI The URI of the server to restore.
- * @throws QueryException if the restore cannot be completed.
- */
- public void restore(InputStream inputStream, URI serverURI) throws QueryException {
-
- if ( inputStream == null ) {
- throw new IllegalArgumentException("Null input stream supplied");
- }
- if ( serverURI == null ) {
- throw new IllegalArgumentException("Null server URI supplied");
- }
-
- URI dummySourceURI = null;
- try {
-
- // create dummy URI for server identification messages
- dummySourceURI = new URI(Mulgara.NAMESPACE+"locally-sourced-inputStream.gz");
-
- } catch ( URISyntaxException ex ) {};
-
- this.restore(inputStream, dummySourceURI, serverURI);
-
- }
-
- /**
- * Restore all the data on the specified server. If the database is not
- * currently empty then the database will contain the union of its current
- * content and the content of the backup file when this method returns.
- *
- * @param inputStream a client supplied inputStream to obtain the restore
- * content from. If null assume the sourceURI has been supplied.
- * @param serverURI The URI of the server to restore.
- * @param sourceURI The URI of the backup file to restore from.
- * @throws QueryException if the restore cannot be completed.
- */
- public void restore(InputStream inputStream, URI serverURI, URI sourceURI)
- throws QueryException {
-
- RemoteInputStreamSrvImpl srv = null;
-
- if ( sourceURI == null ) {
- throw new IllegalArgumentException("Null source URI supplied");
- }
- if ( serverURI == null ) {
- throw new IllegalArgumentException("Null server URI supplied");
- }
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Restoring "+sourceURI+" into " +serverURI );
- }
-
- // update the session
- this.updateSession(new ModelResource(serverURI));
-
- if ( inputStream != null ) {
-
- // open and wrap the inputstream
- srv = new RemoteInputStreamSrvImpl(inputStream);
-
- try {
-
- // prepare it for exporting
- UnicastRemoteObject.exportObject(srv);
-
- } catch ( RemoteException rex ) {
- throw new QueryException("Unable to restore an remote InputStream "+
- "into "+ serverURI, rex);
- }
-
- inputStream = new RemoteInputStream(srv);
- }
-
- try {
-
- // perform the restore
- this.getSession().restore( inputStream, serverURI, sourceURI);
-
- } finally {
- if ( srv != null ) {
- try {
- UnicastRemoteObject.unexportObject(srv, false);
- } catch ( NoSuchObjectException ex ) {};
- }
- }
-
- update();
-
- // log that we've loaded the contents of the file
- if (logger.isDebugEnabled()) {
-
- logger.debug("Restored statements from " + sourceURI +
- " into " + serverURI);
- }
- }
-
-
- /**
- * Hijacks the completion of every command to perform actions on interpreter
- * options.
- *
- * @param node a command to be executed by the interpreter
- */
- public void outACommandStart(ACommandStart node) {
-
- // hijack the last message to return the command time
- if (this.getTimeOption()) {
-
- // get the time the command took to execute
- long commandTimeMillis =
- System.currentTimeMillis() - this.getCommandStartTime();
-
- // convert the time to seconds
- double commandTimeSeconds =
- ( (double) commandTimeMillis) / ( (double) 1000L);
-
- // set a new message
- String commandTimeMsg = EOL + "Command execution time - " +
- commandTimeSeconds + " seconds";
- this.setLastMessage(this.getLastMessage() + commandTimeMsg);
- }
-
- // end if
- }
-
- // outACommandStart()
-
- /**
- * Displays help information to the user.
- *
- * @param node the help command
- */
- public void outAHelpCommand(AHelpCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing help command " + node);
- }
-
- // let the user know the help for the selected command
- this.setLastMessage(HelpPrinter.getHelp(node.getCommandPrefix()));
- }
-
- // outAHelpCommand()
-
- /**
- * Quits a session.
- *
- * @param node the quit command
- */
- public void outAQuitCommand(AQuitCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
- logger.debug("Processing quit command " + node);
- }
-
- // idicate that a quit command was received
- this.setQuitRequested(true);
-
- // let the user know that we're closing down
- this.setLastMessage("Quitting ITQL session");
- }
-
- // outAQuitCommand()
-
- /**
- * Commits a transaction.
- *
- * @param node the commit command
- */
- public void outACommitCommand(ACommitCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing commit command " + node);
- }
-
- try {
-
- // commit this transaction
- this.getSession().commit();
-
- // log that we've executed the query
- if (logger.isDebugEnabled()) {
-
- logger.debug("Successfully committed transaction");
- }
-
- // inform the user of the result
- this.setLastAnswer(null);
- this.setLastMessage("Successfully committed transaction");
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Unable to commit transaction." + EOL +
- ItqlUtil.getCause(qe, 2));
- logger.warn("Unable to commit transaction", qe);
- }
- catch (RuntimeException re) {
-
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Failed to commit transaction:" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to commit transaction", re);
- }
-
- // try-catch
- }
-
- // outAQuitCommand()
-
- /**
- * Rolls back a transaction.
- *
- * @param node the rollback command
- */
- public void outARollbackCommand(ARollbackCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing rollback command " + node);
- }
-
- try {
-
- // rollback any changes made
- this.getSession().rollback();
-
- // log that we've executed the query
- if (logger.isDebugEnabled()) {
-
- logger.debug("Successfully rolled back changes");
- }
-
- // inform the user of the result
- this.setLastAnswer(null);
- this.setLastMessage("Successfully rolled back changes");
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Unable to roll back changes." + EOL +
- ItqlUtil.getCause(qe, 2));
- logger.warn("Unable to roll back changes", qe);
- }
- catch (RuntimeException re) {
-
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Unable to roll back changes:" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to roll back changes", re);
- }
- }
-
- /**
- * Executes a query.
- *
- * @param node the query command
- */
- public void outASelectCommand(ASelectCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
- logger.debug("Processing select command " + node);
- }
-
- try {
-
- // build the query
- Query query = this.buildQuery(node.getQuery());
-
- if (executeQuery) {
-
- // log that we've created the query and will execute it
- if (logger.isDebugEnabled()) {
- logger.debug("Executing query " + query);
- logger.debug("Executing query " + query.getVariableList());
- }
-
- updateSession(query.getModelExpression());
-
- // build the query
- Answer answer = this.getSession().query(query);
-
- // make sure we got an answer
- if (answer == null) {
- throw new QueryException("Invalid answer received");
- } // end if
-
- // log that we've executed the query
- if (logger.isDebugEnabled()) {
- logger.debug("Successfully executed query " + node);
- }
-
- // move to the first row
- answer.beforeFirst();
-
- // inform the user of the answer
- this.setLastAnswer(answer);
- }
- }
- catch (TuplesException te) {
-
- // let the user know the problem
- this.setLastError(te);
- this.setLastAnswer(null);
- this.setLastMessage("Couldn't answer select query." + EOL + ItqlUtil.getCause(te, 2) + EOL + te);
- logger.warn("Couldn't answer query", te);
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Couldn't answer select query." + EOL + ItqlUtil.getCause(qe, 2) + EOL + qe);
- logger.warn("Couldn't answer query", qe);
- }
- catch (URISyntaxException use) {
-
- // let the user know the problem
- this.setLastError(use);
- this.setLastAnswer(null);
- this.setLastMessage("Couldn't answer query: Invalid resource URI.");
- logger.warn("Invalid resource URI." + EOL + ItqlUtil.getCause(use, 0));
- }
- catch (RuntimeException re) {
-
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Couldn't answer query :" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to select statements", re);
- }
-
- // try-catch
- }
-
- // outASelectCommand()
-
- /**
- * Notify that the current session has been updated.
- */
- private void update() {
- transactionUpdated = !autoCommit;
- }
-
- /**
- * If the <code>FROM</code> clause of query refers to models in a different
- * server than the one we're pointed at, change the {@link #session}.
- *
- * @param modelExpression a <code>FROM</code> clause, never <code>null</code>
- * @throws QueryException if the <var>modelExpression</var> can't be resolved
- * by any single server
- */
- private void updateSession(ModelExpression modelExpression) throws
- QueryException {
- assert modelExpression != null;
-
- if (providedSession != null) {
- session = providedSession;
- return;
- }
-
- URI databaseURI = null;
-
- // Check to see that we're aimed at the right server
- Set databaseURISet = modelExpression.getDatabaseURIs();
- assert databaseURISet != null;
- if (logger.isDebugEnabled()) {
- logger.debug(
- "Current server is " + serverURI + ", updating for " + databaseURISet
- );
- }
- switch (databaseURISet.size()) {
- case 0:
-
- // Query presumably contains only URLs -- any server can deal with
- // this, including the current one
- if (session == null) {
- try {
- serverURI = SessionFactoryFinder.findServerURI();
-
- SessionFactory sessionFactory =
- SessionFactoryFinder.newSessionFactory(serverURI, !isLocal);
-
- // Switch the underlying session to point at the required server
- setSession(sessionFactory.newSession(),
- sessionFactory.getSecurityDomain());
- }
- catch (SessionFactoryFinderException e) {
- throw new QueryException("Unable to connect to a server", e);
- }
- catch (NonRemoteSessionException e) {
- throw new QueryException("Error connecting to the local server", e);
- }
- }
- assert session != null;
- break;
-
- case 1:
-
- // Query must go to a particular server
- databaseURI = (URI) databaseURISet.iterator().next();
- assert databaseURI != null;
- if (!databaseURI.equals(serverURI)) {
- setServerURI(databaseURI);
- }
- assert databaseURI.equals(serverURI);
- break;
-
- default:
-
- // Query must be distributed between multiple servers
- assert databaseURISet.size() > 1;
-
- if (!databaseURISet.contains(serverURI)) {
- // We're not even aimed at one of the servers involved in this query,
- // so choose one arbitrarily and switch to it
- databaseURI = (URI) databaseURISet.iterator().next();
- assert databaseURI != null;
- setServerURI(databaseURI);
- assert databaseURI.equals(serverURI);
- }
-
- // We're now connected to one of the servers involved in this query.
- assert databaseURISet.contains(serverURI);
- break;
- }
- }
-
- public void setServerURI(URI databaseURI) throws QueryException {
-
- // Short-circuit evaluation if the new value equals the old value
- if (serverURI == null) {
- if (databaseURI == null) {
- return;
- }
- } else {
- if (serverURI.equals(databaseURI)) {
- return;
- }
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("Changing server URI from " + serverURI + " to " +
- databaseURI);
- }
-
- // connect to local server via EmbeddedMulgaraServer Database which is an instance of SessionFactory
- // - get a session factory from that singleton database
- // Switch the underlying session to point at the required server
- if (databaseURI == null) {
- setSession(null, null);
- } else {
- if (providedSession != null) {
- if (session != providedSession) {
- session = providedSession;
- }
- } else {
- try {
- if (logger.isDebugEnabled()) {
- logger.debug("Finding session factory for " + databaseURI);
- }
-
- SessionFactory sessionFactory =
- SessionFactoryFinder.newSessionFactory(databaseURI, !isLocal);
-
- if (logger.isDebugEnabled()) {
- logger.debug("Found " + sessionFactory.getClass() +
- " session factory, obtaining session with " +
- databaseURI);
- }
-
- Session session = sessionFactory.newSession();
-
- if (logger.isDebugEnabled()) {
- logger.debug("Obtained session with " + databaseURI);
- }
-
- setSession(session, sessionFactory.getSecurityDomain());
- } catch (SessionFactoryFinderException e) {
- throw new QueryException("Unable to reconnect to " + databaseURI, e);
- } catch (NonRemoteSessionException e) {
- throw new QueryException("Error connecting to the local server", e);
- }
- }
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("Changed server URI from " + serverURI + " to " +
- databaseURI);
- }
-
- serverURI = databaseURI;
- }
-
- /**
- * Returns the session to use to communicate with the specified Mulgara server.
- *
- * @param serverURI URI Server to get a Session for.
- * @return the session to use to communicate with the specified Mulgara server
- */
- public Session getSession(URI serverURI) throws QueryException {
-
- //set up session to the server
- this.updateSession(new ModelResource(serverURI));
- return this.getSession();
- }
-
- /**
- * Substitutes the user associated with this session.
- *
- * @param node the su command
- */
- public void outASuCommand(ASuCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing su command " + node);
- }
-
- URI newSecurityDomainURI = toURI(node.getResource());
-
- loginMap.put(newSecurityDomainURI,
- new Login(node.getUser().getText(),
- node.getPassword().getText().toCharArray()));
-
- if (newSecurityDomainURI.equals(securityDomainURI)) {
- try {
- this.getSession().login(securityDomainURI,
- node.getUser().getText(),
- node.getPassword().getText().toCharArray());
- }
- catch (QueryException e) {
- this.setLastError(e);
- this.setLastMessage("Could not present credential to " +
- securityDomainURI + ": " + e.getMessage());
- }
- }
-
- this.setLastMessage("Credential presented");
-
- } // outASuCommand()
-
- /**
- * Associates an alias prefix with a target.
- *
- * @param node the alias command
- */
- public void outAAliasCommand(AAliasCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing alias command " + node);
- }
-
- // get the prefix and target
- String aliasPrefix = node.getPrefix().getText();
- String aliasTarget = node.getTarget().getText();
-
- try {
-
- // convert the target to a URI
- URI aliasTargetURI = new URI(aliasTarget);
-
- // log the conversion
- if (logger.isDebugEnabled()) {
-
- logger.debug("Converted " + aliasTarget + " to URI " + aliasTargetURI);
- }
-
- // add the alias pair to the map
- this.addAliasPair(aliasPrefix, aliasTargetURI);
-
- // log that we've added the pair to the map
- if (logger.isDebugEnabled()) {
-
- logger.debug("Aliased " + aliasTarget + " as " + aliasPrefix);
- }
-
- // tell the user
- this.setLastMessage("Successfully aliased " + aliasTarget + " as " +
- aliasPrefix);
- }
- catch (URISyntaxException use) {
-
- // log the failed URI creation
- logger.warn("Unable to create URI from alias target " + aliasTarget);
- this.setLastMessage(aliasTarget + " is not a valid URI");
- this.setLastError(use);
- this.setLastAnswer(null);
- }
-
- // try-catch
- }
-
- // outAAliasCommand()
-
- /**
- * Applies a set of rules in a model to data in another model.
- *
- * @param node the alias command
- */
- public void outAApplyCommand(AApplyCommand node) {
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
- logger.debug("Processing apply command " + node);
- }
-
- // get the rule model and target model
- URI ruleModel = toURI(node.getRules());
- URI baseModel = toURI(node.getBase());
- Token dest = node.getDestination();
- URI destModel = (dest == null) ? baseModel : toURI(dest);
-
- try {
- // update the session
- this.updateSession(new ModelResource(ruleModel));
-
- // get the structure from the rule model
- RulesRef rules = this.getSession().buildRules(ruleModel, baseModel, destModel);
-
- // move the session on to the target
- this.updateSession(new ModelResource(destModel));
-
- // create the model
- this.getSession().applyRules(rules);
- update();
-
- this.setLastMessage("Successfully applied " + ruleModel +
- " to " + baseModel + (dest == null ? "" : " => " + destModel));
-
- } catch (Exception e) {
-
- // let the user know the problem
- this.setLastError(e);
- this.setLastAnswer(null);
- int depth = (e instanceof QueryException) ? 2 : 0;
- this.setLastMessage("Could not run " + ruleModel + " on " + baseModel + EOL +
- ItqlUtil.getCause(e, depth));
- if (e instanceof QueryException) {
- logger.warn("Failed to run " + ruleModel + " on " + baseModel, e);
- } else {
- logger.fatal("Failed to run rules:", e);
- }
- }
-
- }
-
- /**
- * Creates a new database/model.
- *
- * @param node the create command
- */
- public void outACreateCommand(ACreateCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing create command " + node);
- }
-
- // get the name of the model to create
- URI modelURI = toURI(node.getModel());
-
- // get the type of model to create; default to mulgara:Model is unspecified
- URI modelTypeURI = (node.getModelType() == null)
- ? Session.MULGARA_GRAPH_URI
- : toURI(node.getModelType());
-
- try {
-
- // log that we're asking the driver to create the resource
- if (logger.isDebugEnabled()) {
-
- logger.debug("Creating new model " + modelURI);
- }
-
- modelURI = getCanonicalUriAlias(modelURI);
-
- if (logger.isDebugEnabled()) {
- logger.debug("Model is alias for " + modelURI);
- }
-
- // ensure that we're aimed at the server this model will reside upon
- this.updateSession(new ModelResource(modelURI));
-
- // create the model
- this.getSession().createModel(modelURI, modelTypeURI);
- update();
-
- // log that we've created the database
- if (logger.isDebugEnabled()) {
-
- logger.debug("Created new model " + modelURI + " of type " +
- modelTypeURI);
- }
-
- // tell the user
- this.setLastMessage("Successfully created model " + modelURI);
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Could not create " + modelURI + EOL +
- ItqlUtil.getCause(qe, 2));
- logger.warn("Failed to create " + modelURI + " as type " + modelTypeURI,
- qe);
- }
- catch (RuntimeException re) {
-
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Failed to create model:" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to create model", re);
- }
-
- // try-catch
- }
-
- // outACreateCommand()
-
- /**
- * Drop (delete) a database/model.
- *
- * @param node the drop command
- */
- public void outADropCommand(ADropCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing drop command " + node);
- }
-
- // get the name of the database/model to drop
- URI resourceURI = toURI(node.getResource());
-
- try {
- // ensure we have a session to the server where the model resides
- this.updateSession(new ModelResource(resourceURI));
-
- // drop the resource
- this.getSession().removeModel(resourceURI);
- update();
-
- // log that we've dropped the database
- if (logger.isDebugEnabled()) {
-
- logger.debug("Dropped model " + resourceURI);
- }
-
- // tell the user
- this.setLastMessage("Successfully dropped model " + resourceURI);
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Could not remove " + resourceURI + EOL +
- ItqlUtil.getCause(qe, 2));
- logger.warn("Failed to remove " + resourceURI, qe);
- }
- catch (RuntimeException re) {
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Failed to remove model:" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to remove model", re);
- }
-
- // try-catch
- }
-
- // outADropCommand()
-
- /**
- * Load the contents of a file into a database/model.
- *
- * @param node the load command
- */
- public void outALoadCommand(ALoadCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- RemoteInputStream remoteInputStream = null;
- RemoteInputStreamSrvImpl srv = null;
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing load command " + node);
- }
-
- // get constituents of the load command
- URI sourceURI = toURI(node.getSource());
- URI destinationURI = toURI(node.getDestination());
-
- try {
-
- long stmtCount = 0;
-
- // update the session
- this.updateSession(new ModelResource(destinationURI));
-
-
- // are we loading the file locally from the client?
- if ( node.getLocality() != null &&
- (node.getLocality() instanceof ALocalLocality) ) {
-
- if ( logger.isInfoEnabled() ) {
- logger.info("loading local resource : " + sourceURI );
- }
-
- try {
-
- //open an InputStream
- InputStream inputStream = sourceURI.toURL().openStream();
-
- //is the file/stream compressed?
- String path = (sourceURI == null) ? "" : sourceURI.toString();
- inputStream = adjustForCompression(path, inputStream);
-
- // open and wrap the inputstream
- srv = new RemoteInputStreamSrvImpl(inputStream);
-
- // prepare it for exporting
- UnicastRemoteObject.exportObject(srv);
-
- remoteInputStream = new RemoteInputStream(srv);
-
- // modify the database
- stmtCount =
- this.getSession().setModel(remoteInputStream,
- destinationURI, // model to redefine
- new ModelResource(sourceURI));
- }
- catch (IOException ex) {
- logger.error("Error attempting to load : " + sourceURI, ex);
- throw new QueryException("Error attempting to load : " + sourceURI, ex);
- } finally {
- if ( srv != null ) {
- try {
- UnicastRemoteObject.unexportObject(srv, false);
- } catch ( NoSuchObjectException ex ) {};
- }
- }
- }
- else {
-
- if ( logger.isInfoEnabled() ) {
- logger.info("loading remote resource : " + sourceURI );
- }
-
- // modify the database using a remote file located on the server
- // default behaviour
-
- stmtCount =
- this.getSession().setModel(destinationURI, // model to redefine
- new ModelResource(sourceURI));
- }
- update();
-
- // log that we've loaded the contents of the file
- if (logger.isDebugEnabled()) {
-
- logger.debug("Loaded " + stmtCount + " statements from " + sourceURI +
- " into " + destinationURI);
- }
-
- // tell the user
- if (stmtCount > 0L) {
-
- this.setLastMessage("Successfully loaded " + stmtCount +
- " statements from " + sourceURI + " into " +
- destinationURI);
- }
- else {
-
- this.setLastMessage("WARNING: No valid RDF statements found in " +
- sourceURI);
- } // end if
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Could not load " + sourceURI + " into " +
- destinationURI + EOL + ItqlUtil.getCause(qe, 2));
- logger.warn("Failed to load " + sourceURI + " into " + destinationURI,
- qe);
- }
- catch (RuntimeException re) {
-
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Failed to load statements:" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to load statements", re);
- }
- finally {
-
- // close the inputstream in-case the server was not able to
- // complete the task.
- if ( remoteInputStream != null ) {
- try {
- remoteInputStream.close();
- } catch ( Exception ex ) {};
- }
-
- }
- // try-catch
-
- }
-
- // outALoadCommand()
-
- /**
- * Executes an iTQL script.
- *
- * @param node the execute command
- */
- public void outAExecuteCommand(AExecuteCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing execute command " + node);
- }
-
- // get the name of the script to execute
- String resource = node.getResource().getText();
-
- // keep a record of the line number
- int line = 0;
-
- try {
-
- // convert the script to a URL
- URL scriptURL = new URL(resource);
-
- // log that we're executing a script
- if (logger.isDebugEnabled()) {
-
- logger.debug("Executing script " + scriptURL);
- }
-
- // create a buffer to hold the results in
- StringBuffer resultsMsg = new StringBuffer();
-
- // create a reader to read the contents of the script
- BufferedReader scriptIn =
- new BufferedReader(new InputStreamReader(scriptURL.openStream()));
-
- // execute the script!
- String command = scriptIn.readLine();
-
- while (command != null) {
-
- // increment the line number
- line++;
-
- if (!command.equals("")) {
-
- // execute the command
- executeCommand(command);
- }
-
- // end if
- // get the next command
- command = scriptIn.readLine();
- }
-
- // end if
- // tell the user
- resultsMsg.append("Completed execution of script " + resource);
- this.setLastMessage(resultsMsg.toString());
- }
- catch (MulgaraParserException pe) {
-
- // let the user know the problem
- this.setLastError(pe);
- this.setLastAnswer(null);
- this.setLastMessage("Syntax error in script (line " + line + "): " +
- pe.getMessage());
- logger.warn("Unable to execute script - " + resource + EOL +
- ItqlUtil.getCause(pe, 0));
- }
- catch (LexerException le) {
-
- // let the user know the problem
- this.setLastError(le);
- this.setLastAnswer(null);
- this.setLastMessage("Syntax error in script (line " + line + "): " +
- le.getMessage());
- logger.warn("Unable to execute script - " + resource + EOL +
- ItqlUtil.getCause(le, 0));
- }
- catch (MalformedURLException mue) {
-
- // let the user know the problem
- this.setLastError(mue);
- this.setLastAnswer(null);
- this.setLastMessage("Could not execute script: Invalid script URL.");
- logger.warn("Invalid script source URL." + EOL + ItqlUtil.getCause(mue, 0));
- }
- catch (Exception e) {
-
- // let the user know the problem
- this.setLastError(e);
- this.setLastAnswer(null);
- this.setLastMessage("Could not execute script." + EOL +
- ItqlUtil.getCause(e, 0));
- logger.error("Unable to execute script - " + resource + EOL +
- ItqlUtil.getCause(e, 0));
- }
- // try-catch
- }
-
- // outAExecuteCommand()
-
- /**
- * Inserts a triple, model, database or the results of a query into a model or
- * database.
- *
- * @param node the insert command
- */
- public void outAInsertCommand(AInsertCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing insert command " + node);
- }
-
- // get the resource we're inserting data into
- URI resourceURI = toURI(node.getResource());
-
- try {
-
- // log that we're inserting the statments
- if (logger.isDebugEnabled()) {
-
- logger.debug("Inserting statements into " + resourceURI);
- }
-
- // update the session
- this.updateSession(new ModelResource(resourceURI));
-
- // insert the statements into the model
- insertStatements(resourceURI, node.getTripleFactor());
- update();
-
- // log that we've inserted the statments
- if (logger.isDebugEnabled()) {
-
- logger.debug("Completed inserting statements into " + resourceURI);
- }
-
- // tell the user
- this.setLastMessage(
- "Successfully inserted statements into " + resourceURI
- );
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Could not insert statements into " + resourceURI +
- EOL + ItqlUtil.getCause(qe, 2));
- logger.warn("Failed to insert statements into " + resourceURI, qe);
- }
- catch (URISyntaxException use) {
-
- // let the user know the problem
- this.setLastError(use);
- this.setLastAnswer(null);
- this.setLastMessage("Could not insert into resource: Invalid resource " +
- "URI.");
- logger.warn("Invalid resource URI." + EOL + ItqlUtil.getCause(use, 0));
- }
- catch (RuntimeException re) {
-
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Failed to insert statements:" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to insert statements", re);
- }
- }
-
- // outAInsertCommand()
-
- /**
- * Deletes a triple, model, database or the results of a query from a model or
- * database.
- *
- * @param node the delete command
- */
- public void outADeleteCommand(ADeleteCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing delete command " + node);
- }
-
- // get the resource we're deleting data from
- URI resourceURI = toURI(node.getResource());
-
- try {
-
- // log that we're deleting the statments
- if (logger.isDebugEnabled()) {
-
- logger.debug("Deleting statements from " + resourceURI);
- }
-
- // update the session
- this.updateSession(new ModelResource(resourceURI));
-
- // delete the statements from the model
- deleteStatements(resourceURI, node.getTripleFactor());
- update();
-
- // log that we've inserted the statments
- if (logger.isDebugEnabled()) {
-
- logger.debug("Completed deleting statements from " + resourceURI);
- }
-
- // tell the user
- this.setLastMessage(
- "Successfully deleted statements from " + resourceURI
- );
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Could not delete statements from " + resourceURI +
- EOL + ItqlUtil.getCause(qe, 2));
- logger.warn("Failed to delete statements from " + resourceURI, qe);
- }
- catch (URISyntaxException use) {
-
- // let the user know the problem
- this.setLastError(use);
- this.setLastAnswer(null);
- this.setLastMessage("Could not delete from resource: Invalid resource " +
- "URI.");
- logger.warn("Invalid resource URI." + EOL + ItqlUtil.getCause(use, 0));
- }
- catch (RuntimeException re) {
-
- // let the user know the problem
- this.setLastError(re);
- this.setLastAnswer(null);
- this.setLastMessage("Failed to delete statements:" + ItqlUtil.getCause(re, 0));
- logger.fatal("Failed to delete statements", re);
- }
-
- // try-catch
- }
-
- // outADeleteCommand()
-
- /**
- * Sets an interpreter property.
- *
- * @param node the set command
- */
- public void outASetCommand(ASetCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing set command " + node);
- }
-
- // get the option to set
- PSetOption option = node.getSetOption();
-
- // log that we've got the option
- if (logger.isDebugEnabled()) {
-
- logger.debug("Found option " + option);
- }
-
- // get the value
- PSetOptionMode optionMode = node.getSetOptionMode();
- boolean optionSet = false;
-
- if (optionMode instanceof AOffSetOptionMode) {
-
- optionSet = false;
- }
- else {
-
- optionSet = true;
- } // end if
-
- // set the option
- if (option instanceof ATimeSetOption) {
-
- // set the time option
- this.setTimeOption(optionSet);
-
- // return the user a message
- this.setLastMessage("Command timing is " + (optionSet ? "on" : "off"));
- }
- else if (option instanceof AAutocommitSetOption) {
-
- /* Do not assume this. As the server may have
- encountered an error.
- if (optionSet == autoCommit) {
- if (logger.isDebugEnabled()) {
- logger.debug("Autocommit option is already " + autoCommit);
- } // end if
- return;
- }
- */
-
- try {
-
- // log that we got a autocommit option
- if (logger.isDebugEnabled()) {
-
- logger.debug("Found autocommit option, setting to " +
- (optionSet ? "on" : "off"));
- } // end if
-
- // set the auto commit status
- if (session != null) {
- this.getSession().setAutoCommit(optionSet);
- // set the state of a transaction to clean, only if we have just finished a transaction
- if (!autoCommit && optionSet) {
- autoCommit = optionSet;
- update();
- }
- }
- autoCommit = optionSet;
-
- if (logger.isDebugEnabled()) {
- logger.debug("Set autocommit to " + (optionSet ? "on" : "off"));
- }
-
- // return the user a message
- this.setLastMessage("Auto commit is " + (optionSet ? "on" : "off"));
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Unable to set interpreter option" + EOL +
- ItqlUtil.getCause(qe, 2));
- logger.warn("Unable to set interpreter property", qe);
- }
-
- // try-catch
- }
- else {
-
- // this should never get through the parser, if it does it probably
- // means the grammar has been updated
- this.setLastMessage("Unknown interpreter option");
- }
-
- // end if
- // log the option setting
- if (logger.isDebugEnabled()) {
-
- logger.debug(option + "has been set to " + optionSet);
- }
- }
-
- // outASetCommand()
-
- /**
- * Backs up the contents of a server to a local or remote file.
- *
- * @param node the backup command
- */
- public void outABackupCommand(ABackupCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- RemoteOutputStream outputStream = null;
- RemoteOutputStreamSrvImpl srv = null;
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing backup command " + node);
- }
-
- // get the server we'll be backing up
- URI sourceURI = toURI(node.getSource());
-
- // get the resource we're writing to
- URI destinationURI = toURI(node.getDestination());
-
- try {
-
- // set the server uri given a possible model
- this.setBackupServer(sourceURI);
-
- // are we backing up a file locally to the client?
- if ( node.getLocality() != null &&
- (node.getLocality() instanceof ALocalLocality) ) {
-
- if ( logger.isInfoEnabled() ) {
- logger.info("backing up local resource : " + sourceURI );
- }
-
- try {
-
- // open and wrap the outputstream
- srv = new RemoteOutputStreamSrvImpl(
- new FileOutputStream(destinationURI.getPath()));
-
- // prepare it for exporting
- UnicastRemoteObject.exportObject(srv);
-
- outputStream = new RemoteOutputStream(srv);
-
- }
- catch (IOException ex) {
- logger.error("Error attempting to backing up : " + sourceURI, ex);
- }
-
- try {
-
- // back it up to the local file system
- this.getSession().backup(sourceURI, outputStream);
-
- } finally {
-
- // ensure the stream is closed in case the server was not able
- // to close it.
- if ( outputStream != null ) {
- try {
- outputStream.close();
- } catch ( IOException ioex ) {};
- if ( srv != null ) {
- try {
- UnicastRemoteObject.unexportObject(srv, false);
- } catch ( NoSuchObjectException ex ) {};
- }
- }
- }
-
- }
- else {
-
- // back it up via the server
- this.getSession().backup(sourceURI, destinationURI);
- }
-
- // log that we've inserted the statments
- if (logger.isDebugEnabled()) {
-
- logger.debug("Completed backing up " + sourceURI +
- " to " + destinationURI);
- }
-
- // tell the user
- this.setLastMessage("Successfully backed up " + sourceURI +
- " to " + destinationURI + ".");
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Could not backup " + sourceURI + " to " +
- destinationURI + EOL + ItqlUtil.getCause(qe, 2) + ".");
- logger.warn("Failed to backup server " + sourceURI + " to " +
- destinationURI,
- qe);
- }
-
- // try-catch
- }
-
- // outABackupCommand()
-
- /**
- * Restores the contents of a server from a file.
- *
- * @param node the restore command
- */
- public void outARestoreCommand(ARestoreCommand node) {
-
- this.setLastError(null);
- this.setLastAnswer(null);
- this.setLastMessage("");
-
- RemoteInputStream inputStream = null;
- RemoteInputStreamSrvImpl srv = null;
-
- // log the command
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing restore command " + node);
- }
-
- // get the server we'll be restoring to
- URI destinationURI = toURI(node.getDestination());
-
- // get the resource we're reading from
- URI sourceURI = toURI(node.getSource());
-
- try {
-
- // log that we're backing up a server
- if (logger.isDebugEnabled()) {
-
- logger.debug("Restoring server " + destinationURI + " from " +
- sourceURI);
- }
-
- setServerURI(destinationURI);
-
- // are we loading the file locally from the client?
- if ( node.getLocality() != null &&
- (node.getLocality() instanceof ALocalLocality) ) {
-
- if ( logger.isInfoEnabled() ) {
- logger.info("restoring local resource : " + sourceURI );
- }
-
- try {
-
- // open and wrap the inputstream
- srv = new RemoteInputStreamSrvImpl(sourceURI.toURL().openStream());
-
- // prepare it for exporting
- UnicastRemoteObject.exportObject(srv);
-
- inputStream = new RemoteInputStream(srv);
-
- // modify the database
- this.getSession().restore( inputStream, destinationURI, sourceURI);
- }
- catch (IOException ex) {
- logger.error("Error attempting to restore : " + sourceURI, ex);
- throw new QueryException("Error attempting to restore : " + sourceURI, ex);
- }
- finally {
- if ( srv != null ) {
- try {
- UnicastRemoteObject.unexportObject(srv, false);
- } catch ( NoSuchObjectException ex ) {};
- }
- }
- }
- else {
-
- // restore it from the server
- this.getSession().restore(destinationURI, sourceURI);
-
- }
-
- update();
-
- // log that we've inserted the statments
- if (logger.isDebugEnabled()) {
-
- logger.debug("Completed restoring " + destinationURI + " from " +
- sourceURI);
- }
-
- // tell the user
- this.setLastMessage("Successfully restored " + destinationURI + " from " +
- sourceURI);
- }
- catch (QueryException qe) {
-
- // let the user know the problem
- this.setLastError(qe);
- this.setLastAnswer(null);
- this.setLastMessage("Could not restore " + destinationURI + " from " +
- sourceURI + EOL + ItqlUtil.getCause(qe, 2));
- logger.warn("Failed to restore server " + destinationURI + " from " +
- sourceURI, qe);
- }
- finally {
-
- // close the inputstream in-case the server was not able to
- // complete the task.
- if ( inputStream != null ) {
- try {
- inputStream.close();
- }
- catch ( Exception ex ) {};
- }
- }
- }
-
- /**
- * Sets the error of the last query. Methods overriding <code>DepthFirstAdapter</code>
- * are expected to set a result for successful queries, and <code>null</code>
- * for failed ones.
- *
- * @param lastError the exception of the last command execution
- */
- void setLastError(Exception lastError) {
-
- // carefully set the answer by value rather than reference
- this.lastError =
- (lastError == null) ? null : new ItqlInterpreterException(lastError);
- }
-
- /**
- * Sets the results of the last command execution. Methods overriding <code>DepthFirstAdapter</code>
- * are expected to set a results message, even if that message is null.
- *
- * @param lastMessage the results of the last command execution
- */
- void setLastMessage(String lastMessage) {
-
- this.lastMessage = lastMessage;
- }
-
- // setLastMessage()
-
- /**
- * Returns the driver used to communicate with the database.
- *
- * @return the driver used to communicate with the database
- */
- Session getSession() throws QueryException {
-
- if (providedSession != null) {
- if (session != providedSession) {
- session = providedSession;
- }
- }
-
- if (this.session == null) {
- throw new QueryException("Null session");
- }
- return this.session;
- }
-
- // getCause()
-
- /**
- * Sets the option to enable the timing of commands.
- *
- * @param timeOption the option to enable the timing of commands
- */
- private void setTimeOption(boolean timeOption) {
-
- this.timeOption = timeOption;
- }
-
- // getTimeOption()
-
- /**
- * Sets the time a command started.
- *
- * @param commandStartTime the time a command started
- */
- private void setCommandStartTime(long commandStartTime) {
-
- this.commandStartTime = commandStartTime;
- }
-
- // getCommandStartTime()
-
- /**
- * Sets the driver used to communicate with the database.
- *
- * @param session the driver used to communicate with the database
- * @param securityDomainURI the security domain of the <var>session</var>
- * @throws QueryException if the state of the original session couldn't be
- * propagated to the new <var>session</var>.
- */
- void setSession(Session session, URI securityDomainURI) throws QueryException {
- // override all sessions with the provided one.
- if (providedSession != null) {
- session = providedSession;
- return;
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug(
- "Setting session to " + session + ", security domain " +
- securityDomainURI
- );
- }
-
- // Short-circuit reassignment of the same session
- if (this.session == session) {
- if (logger.isDebugEnabled()) {
- logger.debug("Didn't need to set session");
- }
- return;
- }
-
- // We can't change sessions if we're in the midst of a transaction which
- // has already updated the server
- if (transactionUpdated) {
- throw new QueryException(
- "Can't access more than one server in a transaction"
- );
- }
-
- // Propagate the autoCommit property to the new session
- if (!autoCommit) {
- if (logger.isDebugEnabled()) {
- logger.debug("Setting autocommit to " + autoCommit + " on " + serverURI);
- }
- if (session != null) {
- session.setAutoCommit(autoCommit);
- }
- if (this.session != null) {
- this.session.setAutoCommit(true); // TODO: this requires a compensating
- // transaction in case of
- // failure
- }
- }
-
- // Propagate the login to the new session
- Login login = (Login) loginMap.get(securityDomainURI);
- if (login != null) {
- if (logger.isDebugEnabled()) {
- logger.debug("Logging " + login.username + " into " + serverURI);
- }
- session.login(securityDomainURI, login.username, login.password);
- }
- else {
- if (logger.isDebugEnabled()) {
- logger.debug("No credentials to propagate for " + securityDomainURI);
- }
- }
-
- if (this.session != null) {
- // Close existing session
- if (logger.isDebugEnabled()) {
- logger.debug("Closing session");
- }
-
- try {
- this.session.close();
- }
- catch (QueryException e) {
- logger.warn("Couldn't close session (abandoning)", e);
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("Closed session");
- }
- }
-
- // Reassign session
- if (session != null) {
- isLocal = session.isLocal();
- }
- this.session = session;
- this.securityDomainURI = securityDomainURI;
- }
-
- // getSession()
-
- /**
- * Sets the alias map associated with this session.
- *
- * @param aliasMap the alias map associated with this session
- */
- public void setAliasMap(Map aliasMap) {
-
- this.aliasMap = aliasMap;
- }
-
- // addAliasPair()
-
- /**
- * Sets the flag indicating whether the user has entered the quit command
- *
- * @param quitRequested The new QuitRequested value
- */
- private void setQuitRequested(boolean quitRequested) {
-
- this.quitRequested = quitRequested;
- }
-
- // setQuitRequested()
-
- /**
- * Sets the results of the last query. Methods overriding <code>DepthFirstAdapter</code>
- * are expected to set a result for successful queries, and <code>null</code>
- * for failed ones.
- *
- * @param lastAnswer the results of the last command execution
- */
- private void setLastAnswer(Answer lastAnswer) {
-
- this.lastAnswer = lastAnswer;
- }
-
- /**
- * Insert a set of triples. Calls the server if it can be done only on the
- * server.
- *
- * @param tripleFactor a triple, model or query from the parser
- * @throws QueryException if <code>tripleFactor</code> contains a query that
- * cannot be executed, or after evaluation contains no statements
- * @throws URISyntaxException if <code>tripleFactor</code> contains a query or
- * a resource that that violates <a
- * href="http://www.isi.edu/in-notes/rfc2396.txt">RFC\uFFFD2396</a>
- */
- private void insertStatements(URI modelURI, PTripleFactor tripleFactor) throws
- QueryException, URISyntaxException {
-
- // validate tripleFactor parameter
- if (tripleFactor == null) {
-
- throw new IllegalArgumentException("Null \"tripleFactor\" parameter");
- }
-
- // log that we're finding statements
- if (logger.isDebugEnabled()) {
-
- logger.debug("Finding statements in expression " + tripleFactor);
- }
-
- // get the set of triples out of the factor
- PSetOfTriples setOfTriples = null;
-
- if (tripleFactor instanceof ABracedTripleFactor) {
-
- setOfTriples = ( (ABracedTripleFactor) tripleFactor).getSetOfTriples();
- }
- else if (tripleFactor instanceof AUnbracedTripleFactor) {
-
- setOfTriples = ( (AUnbracedTripleFactor) tripleFactor).getSetOfTriples();
- }
-
- // drill down into the set of triples
- if (setOfTriples instanceof AResourceSetOfTriples) {
-
- // log that we've found a resource
- if (logger.isDebugEnabled()) {
-
- URI resourceURI =
- toURI( ( (AResourceSetOfTriples) setOfTriples).getResource());
- logger.debug("Found resource " + resourceURI + "in triple factor");
- }
-
- // TODO: implement this once we can select all triples from a model
- // we cannot currently handle inserting or deleting a complete model
- // into/from another
- throw new UnsupportedOperationException("Models cannot be inserted " +
- "into or deleted from other models");
- }
- else if (setOfTriples instanceof ASelectSetOfTriples) {
-
- // build the query
- Query query = this.buildQuery( ( (ASelectSetOfTriples) setOfTriples));
-
- // log that we've created the query and will execute it
- if (logger.isDebugEnabled()) {
-
- logger.debug("Executing query " + query);
- }
-
- getSession().insert(modelURI, query);
- }
- else if (setOfTriples instanceof ATripleSetOfTriples) {
-
- Map variableMap = new HashMap();
- Set statements = getStatements( (ATripleSetOfTriples) setOfTriples,
- variableMap);
- getSession().insert(modelURI, statements);
- }
- }
-
- /**
- * Delete a set of triples. Calls the server if it can be done only on the
- * server.
- *
- * @param tripleFactor a triple, model or query from the parser
- * @throws QueryException if <code>tripleFactor</code> contains a query that
- * cannot be executed, or after evaluation contains no statements
- * @throws URISyntaxException if <code>tripleFactor</code> contains a query or
- * a resource that that violates <a
- * href="http://www.isi.edu/in-notes/rfc2396.txt">RFC\uFFFD2396</a>
- */
- private void deleteStatements(URI modelURI, PTripleFactor tripleFactor) throws
- QueryException, URISyntaxException {
-
- // validate tripleFactor parameter
- if (tripleFactor == null) {
-
- throw new IllegalArgumentException("Null \"tripleFactor\" parameter");
- }
-
- // log that we're finding statements
- if (logger.isDebugEnabled()) {
-
- logger.debug("Finding statements in expression " + tripleFactor);
- }
-
- // get the set of triples out of the factor
- PSetOfTriples setOfTriples = null;
-
- if (tripleFactor instanceof ABracedTripleFactor) {
-
- setOfTriples = ( (ABracedTripleFactor) tripleFactor).getSetOfTriples();
- }
- else if (tripleFactor instanceof AUnbracedTripleFactor) {
-
- setOfTriples = ( (AUnbracedTripleFactor) tripleFactor).getSetOfTriples();
- }
-
- // drill down into the set of triples
- if (setOfTriples instanceof AResourceSetOfTriples) {
-
- // log that we've found a resource
- if (logger.isDebugEnabled()) {
-
- URI resourceURI =
- toURI( ( (AResourceSetOfTriples) setOfTriples).getResource());
- logger.debug("Found resource " + resourceURI + "in triple factor");
- }
-
- // TODO: implement this once we can select all triples from a model
- // we cannot currently handle inserting or deleting a complete model
- // into/from another
- throw new UnsupportedOperationException("Models cannot be inserted " +
- "into or deleted from other models");
- }
- else if (setOfTriples instanceof ASelectSetOfTriples) {
-
- // build the query
- Query query = this.buildQuery( ( (ASelectSetOfTriples) setOfTriples));
-
- // log that we've created the query and will execute it
- if (logger.isDebugEnabled()) {
-
- logger.debug("Executing query " + query);
- }
-
- getSession().delete(modelURI, query);
- }
- else if (setOfTriples instanceof ATripleSetOfTriples) {
-
- Map variableMap = new HashMap();
- Set statements = getStatements((ATripleSetOfTriples) setOfTriples,
- variableMap);
- if (variableMap.size() > 0) {
- throw new QueryException("Cannot use variables when deleting " +
- "statements");
- }
- getSession().delete(modelURI, statements);
- }
- }
-
- /**
- * Returns a set of statements from the iTQL query object.
- *
- * @param setOfTriples the set of statements defined in the query.
- * @param variableMap the variable map to store the value of the variable
- * against the variable object.
- * @throws URISyntaxException if <code>tripleFactor</code> contains a query or
- * a resource that that violates <a
- * href="http://www.isi.edu/in-notes/rfc2396.txt">RFC\uFFFD2396</a>
- * @throws QueryException if an invalid node is used in the set of triples.
- * @return a set of statements from the iTQL query.
- */
- public Set getStatements(ATripleSetOfTriples setOfTriples, Map variableMap)
- throws QueryException, URISyntaxException {
-
- List tripleList = setOfTriples.getTriple();
- HashSet statements = new HashSet();
-
- // Check that each set of triples has the predicate bound.
- for (Iterator i = tripleList.iterator(); i.hasNext(); ) {
-
- // get the triple
- ATriple triple = (ATriple) i.next();
-
- // Convert the Subject, Predicate and Object.
- org.jrdf.graph.Node subject = toNode(triple.getSubject(), variableMap);
- org.jrdf.graph.Node predicate = toNode(triple.getPredicate(), variableMap);
- org.jrdf.graph.Node object = toNode(triple.getObject(), variableMap);
-
- // Predicate cannot be a blank node.
- if (predicate instanceof BlankNode) {
- throw new QueryException("Predicate must be a valid URI");
- }
-
- // Check that the subject or predicate node is not a literal.
- if (subject instanceof LiteralImpl ||
- predicate instanceof LiteralImpl) {
-
- // throw an exception indicating we have a bad triple
- throw new QueryException(
- "Subject or Predicate cannot be a literal");
- }
-
- // Create a new statement using the triple elements
- org.jrdf.graph.Triple jrdfTriple = new TripleImpl(
- (SubjectNode) subject, (PredicateNode) predicate,
- (ObjectNode) object);
-
- // add the statement to the statement set
- statements.add(jrdfTriple);
- }
-
- return statements;
- }
-
- /**
- * Builds a set of {@link org.jrdf.graph.Triple}s from a
- * {@link org.mulgara.query.Answer}.
- *
- * @param answer the results of a query
- * @return a set of {@link org.jrdf.graph.Triple}s, suitable for use in
- * inserting or deleting data to or from a model
- * @throws QueryException EXCEPTION TO DO
- */
- private Set getStatements(Answer answer) throws QueryException {
-
- // validate answer parameter
- if (answer == null) {
-
- throw new IllegalArgumentException("Null \"answer\" parameter");
- } // end if
-
- // log that we're parsing an answer into a set of statements
- if (logger.isDebugEnabled()) {
-
- logger.debug("Parsing answer into set of statements");
- }
-
- try {
- Set statements = new HashSet();
- answer.beforeFirst();
-
- while (answer.next()) {
-
- if (! (answer.getObject(0) instanceof ObjectNode)) {
-
- throw new QueryException("Subject is not a resource for [" +
- answer.getObject(0) + " " +
- answer.getObject(1) +
- " " +
- answer.getObject(2) + "]");
- }
-
- if (! (answer.getObject(1) instanceof URIReference)) {
-
- throw new QueryException("Predicate is not a resource for [" +
- answer.getObject(0) + " " +
- answer.getObject(1) +
- " " +
- answer.getObject(2) + "]");
- }
-
- statements.add(new TripleImpl( (SubjectNode) answer.getObject(0),
- (PredicateNode) answer.getObject(1),
- (ObjectNode) answer.getObject(2)));
- }
-
- logger.debug("Parsed answer into " + statements.size());
-
- return statements;
- }
- catch (TuplesException e) {
- throw new QueryException("Couldn't parse answer into statements", e);
- }
- } // setStatements
-
- /**
- * Returns the option to enable the timing of commands.
- *
- * @return the option to enable the timing of commands
- */
- private boolean getTimeOption() {
-
- return timeOption;
- }
-
- /**
- * Return the time a command started.
- *
- * @return the time a command started
- */
- private long getCommandStartTime() {
-
- return commandStartTime;
- }
-
- /**
- * Returns the alias map associated with this session.
- *
- * @return the alias namespace map associated with this session
- */
- public Map getAliasMap() {
-
- return this.aliasMap;
- }
-
- //
- // Internal methods
- //
-
- /**
- * Executes a query and returns its results.
- *
- * @param rawQuery a select query, represented as either a {@link
- * org.mulgara.itql.node.ASelectCommand} or a {@link
- * org.mulgara.itql.node.ASelectSetOfTriples}
- * @return the answer to the query
- * @throws QueryException if the query cannot be executed
- * @throws URISyntaxException if the <code>query</code> contains a resource
- * whose text violates <a href="http://www.isi.edu/in-notes/rfc2396.txt">
- * RFC\uFFFD2396</a>
- */
- public Query buildQuery(org.mulgara.itql.node.Node rawQuery) throws
- QueryException, URISyntaxException {
-
- // validate query parameter
- if (rawQuery == null) {
-
- throw new IllegalArgumentException("Null \"rawQuery\" parameter");
- }
-
- // end if
- // create the variables needed...
- LinkedList variables = null;
- AFromClause fromClause;
- AWhereClause whereClause;
- AOrderClause orderClause;
- AHavingClause havingClause;
- ALimitClause limitClause;
- AOffsetClause offsetClause;
-
- // cast the correct way (we don't have a common superclass, event though we
- // have methods with the same names)
- if (rawQuery instanceof AQuery) {
-
- AQuery query = (AQuery) rawQuery;
- PSelectClause selectClause = query.getSelectClause();
- if (selectClause instanceof ANormalSelectSelectClause) {
- variables = ( (ANormalSelectSelectClause) selectClause).getElement();
- }
- fromClause = ( (AFromClause) query.getFromClause());
- whereClause = ( (AWhereClause) query.getWhereClause());
- orderClause = ( (AOrderClause) query.getOrderClause());
- havingClause = ( (AHavingClause) query.getHavingClause());
- limitClause = ( (ALimitClause) query.getLimitClause());
- offsetClause = ( (AOffsetClause) query.getOffsetClause());
- }
- else if (rawQuery instanceof ASelectSetOfTriples) {
-
- ASelectSetOfTriples query = (ASelectSetOfTriples) rawQuery;
- variables = new LinkedList();
- variables.add(query.getSubject());
- variables.add(query.getPredicate());
- variables.add(query.getObject());
- fromClause = ( (AFromClause) query.getFromClause());
- whereClause = ( (AWhereClause) query.getWhereClause());
- orderClause = ( (AOrderClause) query.getOrderClause());
- havingClause = ( (AHavingClause) query.getHavingClause());
- limitClause = ( (ALimitClause) query.getLimitClause());
- offsetClause = ( (AOffsetClause) query.getOffsetClause());
- }
- else {
-
- // we only handle AQuery and ASelectSetOfTriples
- throw new IllegalArgumentException("Invalid type for \"rawQuery\" " +
- "parameter");
- }
-
- if (fromClause == null) {
-
- throw new QueryException("FROM clause missing.");
- }
-
- if (whereClause == null) {
-
- throw new QueryException("WHERE clause missing.");
- }
-
- // end if
- // log that we're about to build the variable list
- if (logger.isDebugEnabled()) {
- logger.debug("Building query variable list from " + variables);
- }
-
- // build the variable list
- List variableList = this.buildVariableList(variables);
-
- // log that we've built the variable list
- if (logger.isDebugEnabled()) {
- logger.debug("Built variable list " + variableList);
- }
-
- // get the model expression from the parser
- PModelExpression rawModelExpression = fromClause.getModelExpression();
-
- // log that we're about to build the model expression
- if (logger.isDebugEnabled()) {
- logger.debug("Building model expression from " + rawModelExpression);
- }
-
- // parse the text into a model expression
- ModelExpression modelExpression =
- ModelExpressionBuilder.build(this.getAliasMap(), rawModelExpression);
-
- // log that we've built the model expression
- if (logger.isDebugEnabled()) {
- logger.debug("Built model expression " + modelExpression);
- }
-
- // get the constraint expression from the parser
- PConstraintExpression rawConstraintExpression =
- whereClause.getConstraintExpression();
-
- // log that we're about to build the constraint expression
- if (logger.isDebugEnabled()) {
- logger.debug("Building constraint expression from " +
- rawConstraintExpression);
- }
-
- // parse the text into a constraint expression
- ConstraintExpression constraintExpression = build(rawConstraintExpression);
-
- // log that we've build the constraint expression
- if (logger.isDebugEnabled()) {
- logger.debug("Built constraint expression " + constraintExpression);
- }
-
- // build the order list
- List orderList = Collections.EMPTY_LIST;
-
- if (orderClause != null) {
-
- orderList = buildOrderList(orderClause.getOrderElement());
- }
-
- // build the having clause
- ConstraintHaving havingExpression = null;
-
- if (havingClause != null) {
- // get the constraint expression from the parser
- PConstraintExpression rawHavingExpression =
- havingClause.getConstraintExpression();
-
- // log that we're about to build the constraint expression
- if (logger.isDebugEnabled()) {
- logger.debug("Building constraint expression from " +
- rawHavingExpression);
- }
-
- // parse the text into a constraint expression
- havingExpression = buildHaving(rawHavingExpression);
- }
-
- // build the limit
- Integer limit = null;
-
- if (limitClause != null) {
-
- try {
-
- limit = new Integer(limitClause.getNumber().getText());
- }
- catch (NumberFormatException e) {
-
- throw new Error("Sable parser permitted non-integer limit", e);
- }
- }
-
- // build the offset
- int offset = 0;
-
- if (offsetClause != null) {
-
- try {
-
- offset = Integer.parseInt(offsetClause.getNumber().getText());
- }
- catch (NumberFormatException e) {
-
- throw new Error("Sable parser permitted non-integer offset", e);
- }
- }
-
- // build a query using the information we've obtained from the parser
- // (all answers are acceptable)
- lastQuery = new Query(variableList, modelExpression, constraintExpression,
- havingExpression, orderList, limit, offset, new UnconstrainedAnswer());
-
- return lastQuery;
- }
-
- /**
- * Builds a list of {@link org.mulgara.query.Variable}s from a list of
- * {@link org.mulgara.itql.node.PVariable}s. Note. Variables in both the
- * <code>rawVariableList</code> and the returned list will <strong>not
- * </strong> contain the variable prefix <code>$</code> in their name.
- *
- * @param rawVariableList a list of {@link
- * org.mulgara.itql.node.PVariable}s from the parser
- * @return a list of {@link org.mulgara.query.Variable}s, suitable for use
- * in creating a {@link org.mulgara.query.Query}
- * @throws QueryException if the <code>rawVariableList</code> cannot be parsed
- * into a list of {@link org.mulgara.query.Variable}s
- */
- private List buildVariableList(LinkedList rawVariableList) throws
- QueryException, URISyntaxException {
-
- // Empty variable list.
- if (rawVariableList == null) {
- return Collections.EMPTY_LIST;
- }
-
- // validate rawVariableList parameter
- if (rawVariableList.size() == 0) {
- throw new IllegalArgumentException("Empty \"rawVariableList\" parameter");
- }
-
- // Construct the required builder
- VariableBuilder variableBuilder = new VariableBuilder(this,
- variableFactory);
-
- // end if
- // log that we're building the variable list
- if (logger.isDebugEnabled()) {
- logger.debug("Building variable list from " + rawVariableList);
- }
-
- // copy each variable from the query into the list
- for (Iterator i = rawVariableList.iterator(); i.hasNext(); ) {
- PElement element = (PElement) i.next();
- element.apply( (Switch) variableBuilder);
- }
-
- // Get the variable list
- List variableList = variableBuilder.getVariableList();
-
- // make sure that we return a list with something in it
- if (variableList.size() == 0) {
- throw new QueryException("No variables parseable from query");
- }
-
- // log that we've successfully built the variable list
- if (logger.isDebugEnabled()) {
- logger.debug("Built variable list " + variableList);
- }
-
- // return the list
- return variableList;
- }
-
- /**
- * Builds a list of {@link org.mulgara.query.Variable}s from a list of
- * {@link org.mulgara.itql.node.POrderElement}s. Note. Variables in both
- * the <code>rawVariableList</code> and the returned list will <strong>not
- * </strong> contain the variable prefix <code>$</code> in their name.
- *
- * @param rawOrderList PARAMETER TO DO
- * @return a list of {@link org.mulgara.query.Variable}s, suitable for use
- * in creating a {@link org.mulgara.query.Query}
- * @throws QueryException if the <code>rawOrderElementList</code> cannot be
- * parsed into a list of {@link org.mulgara.query.Variable}s
- */
- private List buildOrderList(LinkedList rawOrderList) throws QueryException {
-
- // validate rawOrderElementList parameter
- if ( (rawOrderList == null) || (rawOrderList.size() == 0)) {
-
- throw new IllegalArgumentException("Null \"rawOrderList\" parameter");
- }
-
- // end if
- // log that we're building the variable list
- if (logger.isDebugEnabled()) {
- logger.debug("Building order list from " + rawOrderList);
- }
-
- // create a list for the parsed variables
- List orderList = new ArrayList(rawOrderList.size());
-
- // copy each variable from the query into the list
- for (Iterator i = rawOrderList.iterator(); i.hasNext(); ) {
-
- AOrderElement order = (AOrderElement) i.next();
-
- // get the name of this variable
- String variableName =
- ( (AVariable) order.getVariable()).getIdentifier().getText();
-
- // log that we've found a variable
- if (logger.isDebugEnabled()) {
- logger.debug("Found variable $" + variableName);
- }
-
- // Figure out which way to order, ascending or descending
- boolean ascending;
- PDirection direction = order.getDirection();
-
- if (direction == null) {
- ascending = true;
- }
- else if (direction instanceof AAscendingDirection) {
- ascending = true;
- }
- else if (direction instanceof ADescendingDirection) {
- ascending = false;
- }
- else {
- throw new Error("Unknown direction field in order");
- }
-
- // add a new variable to the list
- orderList.add(new Order(new Variable(variableName), ascending));
- }
-
- // end for
- // make sure that we return a list with something in it
- if (orderList.size() == 0) {
-
- throw new QueryException("No variables parseable from query");
- }
-
- // log that we've successfully built the order list
- if (logger.isDebugEnabled()) {
-
- logger.debug("Built order list " + orderList);
- }
-
- // return the list
- return orderList;
- }
-
- // getStatements()
-
- /**
- * Construct a {@link LiteralImpl} from a {@link PLiteral}.
- *
- * @param p the instance to convert
- */
- public LiteralImpl toLiteralImpl(PLiteral p) {
-
- ALiteral aLiteral = (ALiteral) p;
-
- // Determine the datatype URI, if present
- URI datatypeURI = null;
- if (aLiteral.getDatatype() != null) {
- datatypeURI = toURI( ( (ADatatype) aLiteral.getDatatype()).getResource());
- }
-
- // Determine the language code
- String language = (datatypeURI == null) ? "" : null;
-
- if (datatypeURI == null) {
- return new LiteralImpl(getLiteralText(aLiteral), language);
- }
- else {
- return new LiteralImpl(getLiteralText(aLiteral), datatypeURI);
- }
- }
-
- /**
- * Constructs a {@link org.jrdf.graph.Node} from a {@link
- * org.mulgara.itql.node.PTripleElement}.
- *
- * @param element dd
- * @param variableMap a {@link Map} of variable names (as string) to
- * {@link VariableNodeImpl} that are used to contain all variables.
- * @return dd
- * @throws QueryException if <code>element</code> is a {@link
- * org.mulgara.itql.node.AResourceTripleElement} whose text contains a
- * <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">qualified
- * name</a> with a prefix not defined in the <code>aliasMap</code>
- * @throws URISyntaxException if <code>element</code> is a {@link
- * org.mulgara.itql.node.AResourceTripleElement} whose text doesn't
- * conform to <a href="http://www.isi.edu/in-notes/rfc2396.txt">
- * RFC\uFFFD2396</a>
- */
- private org.jrdf.graph.Node toNode(PTripleElement element, Map variableMap) throws
- QueryException, URISyntaxException {
-
- // validate the element parameter
- if (element == null) {
-
- throw new IllegalArgumentException("Null \"element\" parameter");
- }
-
- // end if
- // log what we're doing
- if (logger.isDebugEnabled()) {
-
- logger.debug("Resolving " + element + "to a RDF node");
- }
-
- // create the node
- org.jrdf.graph.Node node = null;
-
- // get the node
- if (element instanceof ALiteralTripleElement) {
-
- // create a new literal with the given text
- node = toLiteralImpl( ( (ALiteralTripleElement) element).getLiteral());
- }
- else if (element instanceof AResourceTripleElement) {
-
- // create a new resource
- node = new URIReferenceImpl(toURI(
- ( (AResourceTripleElement) element).getResource()
- ));
- }
- else if (element instanceof AVariableTripleElement) {
-
- // get the variable
- String variableName =
- ( (AVariable) ( (AVariableTripleElement) element).getVariable()).
- getIdentifier().getText();
-
- // log what we're doing
- if (logger.isDebugEnabled()) {
-
- logger.debug("Resolved " + element + " to variable " + variableName);
- }
-
- if (variableMap.containsKey(variableName)) {
-
- node = (VariableNodeImpl) variableMap.get(variableName);
- }
- else {
-
- VariableNodeImpl variable = new VariableNodeImpl(variableName);
- variableMap.put(variableName, variable);
- node = variable;
- }
- } // end if
-
- // return the node
- return node;
- }
-
- /**
- * Convert SableCC-generated {@link TResource} tokens into {@link URI}s.
- *
- * Resolution will treat the token as an XML
- * <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">qualified
- * names</a> if the {@link #aliasMap} <code>aliasMap</code> contains a key
- * for the URI scheme part that can be treated as an XML namespace prefix.
- * For example, <kbd>dc:title</kbd> is treated as a qname and mapped to the
- * to the URI <kbd>http://purl.org/dc/elements/1.1/title</kbd>, assuming the
- * {@link #aliasMap} had an entry mapping <code>"dc"</code> to the Dublin
- * Core namespace.
- *
- * @param token the token to be converted, which should actually be a
- * {@link TResource}
- * @throws Error if the <var>token</var> text isn't syntactically
- * a {@link URI}; this shouldn't ever occur, assuming the <var>token</var>
- * is a {@link TResource}
- */
- public URI toURI(Token token) {
-
- assert token instanceof TResource;
-
- try {
- // get the URI of the resource -- this may actually be an XML qname
- URI resourceURI = new URI(token.getText());
-
- if (resourceURI.isOpaque()) {
- // Attempt qname-to-URI substitution for aliased namespace prefixes
- URI mapping = (URI) aliasMap.get(resourceURI.getScheme());
- if (mapping != null) {
- resourceURI = new URI(mapping + resourceURI.getSchemeSpecificPart());
- }
- }
-
- return resourceURI;
- }
- catch (URISyntaxException e) {
- throw new Error("Bad URI syntax in resource: " + e);
- }
- }
-
- /**
- * Determines if the stream is compressed by inspecting the fileName extension.
- *
- * Returns a new "Compressed" stream if the file is compressed or the original
- * InputStream if the file is not compressed.
- *
- * @param fileName String
- * @param inputStream InputStream
- * @throws IOException
- * @return InputStream
- */
- private InputStream adjustForCompression(String fileName,
- InputStream inputStream) throws IOException {
-
- //validate
- if (fileName == null) {
- throw new IllegalArgumentException("File name is null");
- }
- if (inputStream == null) {
- throw new IllegalArgumentException("InputStream is null");
- }
-
- InputStream stream = inputStream;
-
- // Guess at transfer encoding (compression scheme) based on file extension
- if (fileName.toLowerCase().endsWith(".gz")) {
- // The file name ends with ".gz", so assume it's a gzip'ed file
- stream = new GZIPInputStream(inputStream);
- }
- else if (fileName.toLowerCase().endsWith(".zip")) {
- // The file name ends with ".zip", so assume it's a zip'ed file
- stream = new ZipInputStream(inputStream);
- }
-
- assert stream != null;
- return stream;
- }
-
- /**
- * Adds a name/value pair to the alias map. This method will add associate a
- * prefix for a target for subsequent commands, making commands like the
- * following possible: <PRE>
- * alias http://purl.org/dc/elements/1.1 as dc;
- * select $title where $uri dc:title $title ;
- * </PRE>
- *
- * @param aliasPrefix the alias that denotes the target
- * @param aliasTarget the target associated with the prefix
- */
- private void addAliasPair(String aliasPrefix, URI aliasTarget) {
-
- // validate the aliasPrefix parameter
- if (aliasPrefix == null) {
-
- throw new IllegalArgumentException("Null \"aliasPrefix\" " + "parameter");
- }
-
- // end if
- // validate the aliasTarget parameter
- if (aliasTarget == null) {
-
- throw new IllegalArgumentException("Null \"aliasTarget\" " + "parameter");
- }
-
- // end if
- // add the pair to the map
- this.getAliasMap().put(aliasPrefix, aliasTarget);
- }
-
- /**
- * Log the iTQL command to a specified file
- *
- * @param command PARAMETER TO DO
- */
- private void logItql(String command) {
-
- // Has this session been constructed for logging.
- // the constructor initialise this if
- // system property itql.command.log is set
- if (itqlLogFile == null) {
-
- return;
- }
-
- try {
- // has the log file been opened?
- if (itqlLog == null) {
- itqlLog = new PrintWriter(new FileWriter(itqlLogFile, true), true);
- }
-
- // append the command to the file
- itqlLog.println(command);
- }
- catch (Exception ex) {
- logger.error("Unable to log itql commands", ex);
- }
- }
-
- private class Lexer2 extends Lexer {
-
- int commandCount = 0;
- final LinkedList leftoverTokenList = new LinkedList();
-
- public Lexer2() {
- super(null);
- }
-
- public int getCommandCount() {
- return commandCount;
- }
-
- public void add(String command) throws LexerException, IOException {
- Lexer lexer = new Lexer(new PushbackReader(new StringReader(command), 256));
- Token t;
- while (! ( (t = lexer.next()) instanceof EOF)) {
- if (t instanceof TTerminator) {
- t = new EOF();
- commandCount++;
- }
- leftoverTokenList.add(t);
- }
- }
-
- public Token next() throws LexerException, IOException {
- return leftoverTokenList.isEmpty() ? new EOF() : (Token) leftoverTokenList.removeFirst();
- }
-
- public Token peek() throws LexerException, IOException {
- return leftoverTokenList.isEmpty() ? new EOF() : (Token) leftoverTokenList.getFirst();
- }
-
- public boolean nextCommand() {
- if (commandCount == 0) {
- return false;
- }
- else {
- //assert commandCount > 0;
- commandCount--;
- return true;
- }
- }
- }
-
- //
- // Static methods brought in from the late ConstraintExpressionBuilder
- //
-
- /**
- * Returns the text of the given <code>literal</code>.
- *
- * @param literal the literal to retrieve the text from
- * @return The LiteralText value
- */
- public static String getLiteralText(ALiteral literal) {
-
- // validate the literal parameter
- if (literal == null) {
-
- throw new IllegalArgumentException("Null \"literal\" " + "parameter");
- }
-
- // end if
- // the text of the literal
- StringBuffer literalText = new StringBuffer();
-
- // get all the strands in this literal
- List strands = literal.getStrand();
-
- // add each strand together to make the literal text
- for (Iterator i = strands.iterator(); i.hasNext(); ) {
-
- // get the strand
- PStrand strand = (PStrand) i.next();
-
- // add the strand to the literal text
- if (strand instanceof AUnescapedStrand) {
-
- literalText.append( ( (AUnescapedStrand) strand).getText().getText());
- }
- else if (strand instanceof AEscapedStrand) {
-
- literalText.append( ( (AEscapedStrand) strand).getEscapedtext().getText());
- } // end if
-
- } // end for
-
- // return the text
- return literalText.toString();
- }
-
- //
- // Public API
- //
-
- /**
- * Builds a {@link org.mulgara.query.ConstraintExpression} object from a
- * {@link org.mulgara.itql.node.PConstraintExpression}, using an <code>aliasMap</code>
- * to resolve aliases.
- *
- * @param expression a constraint expression from the parser
- * @return RETURNED VALUE TO DO
- * @throws QueryException if <code>rawConstraintExpression</code> does not
- * represent a valid query
- * @throws URISyntaxException if the <code>rawConstraintExpression</code>
- * contains a resource whose text violates <a
- * href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
- */
- public ConstraintExpression build(PConstraintExpression expression) throws
- QueryException, URISyntaxException {
-
- // validate aliasMap parameter
- if (aliasMap == null) {
- throw new IllegalArgumentException("Null \"aliasMap\" parameter");
- }
-
- // validate expression parameter
- if (expression == null) {
- throw new IllegalArgumentException("Null \"expression\" parameter");
- }
-
- // log that we're building a constraint expression
- if (logger.isDebugEnabled()) {
- logger.debug("Building constraint expression from " + expression);
- }
-
- // build the contraint expression from the parser input
- expression.apply( (Switch) builder);
- ConstraintExpression constraintExpression = builder.
- getConstraintExpression();
-
- // log that we've building successfully built a constraint expression
- if (logger.isDebugEnabled()) {
- logger.debug("Successfully built constraint expression from " +
- expression);
- }
-
- // return the contraint expression
- return constraintExpression;
- }
-
- /**
- * Returns an anonymous variable unique for this interpreter.
- * Note: We really should introduce a new subclass of Variable
- * that is explicitly anonymous, but for now this will do.
- */
- public Variable nextAnonVariable() {
- return new Variable("av__" + this.anonSuffix++);
- }
-
- /**
- * Builds a HAVING compliant {@link org.mulgara.query.ConstraintExpression} object from a
- * {@link org.mulgara.itql.node.PConstraintExpression}, using an <code>aliasMap</code>
- * to resolve aliases. To comply with a HAVING clause the predicate must be one of:
- * mulgara:occurs mulgara:occursLessThan mulgara:occursMoreThan.
- *
- * @param expression a constraint expression from the parser
- * @return RETURNED VALUE TO DO
- * @throws QueryException if <code>rawConstraintExpression</code> does not
- * represent a valid query
- * @throws URISyntaxException if the <code>rawConstraintExpression</code>
- * contains a resource whose text violates <a
- * href="http://www.isi.edu/in-notes/rfc2396.txt">RFC?2396</a>
- */
- private ConstraintHaving buildHaving(PConstraintExpression expression)
- throws QueryException, URISyntaxException {
- ConstraintExpression hExpr = build(expression);
-
- if (hExpr instanceof ConstraintOperation) {
- throw new QueryException("Having currently supports only one constraint");
- }
-
- if (!checkHavingPredicates(hExpr)) {
- throw new QueryException("Only \"occurs\" predicates can be used in a Having clause");
- }
- return (ConstraintHaving) hExpr;
- }
-
-
- /**
- * Checks that all predicates in a constraint expression are valid Having predicates
- * from {@link SpecialPredicates}.
- *
- * @param e The constraint expression to check.
- * @return true if all constraints have special predicates.
- */
- private boolean checkHavingPredicates(ConstraintExpression e) {
- if (e instanceof Constraint) {
- return e instanceof ConstraintHaving;
- } else if (e instanceof ConstraintOperation) {
- // check all sub expressions
- Iterator i = ((ConstraintOperation)e).getElements().iterator();
- while (i.hasNext()) {
- if (checkHavingPredicates((ConstraintExpression)i.next())) {
- return false;
- }
- }
- // all sub expressions returned true
- return true;
- } else {
- // An unexpected type
- return false;
- }
- }
-
-
- /**
- * Set the active server for a backup given either a server URI or
- * a model URI.
- *
- * @param sourceURI URI
- */
-
- private void setBackupServer( URI sourceURI ) throws QueryException {
-
- //Determine if a model or a server is being backed up.
- if ( (sourceURI != null)
- && (sourceURI.getFragment() != null)) {
-
- // make a note that a model is being backed up
- if (logger.isDebugEnabled()) {
-
- logger.debug("Model Found. Backing up model " + sourceURI );
- }
-
- //remove fragment from the model URI
- String fragment = sourceURI.getFragment();
- String serverURI = sourceURI.toString().replaceAll("#" + fragment, "");
-
- //create URI for the model's server
- try {
-
- URI uri = new URI(serverURI);
-
- //get session for the model's server.
- setServerURI(uri);
-
- //update the session (required if this is the first query)
- this.updateSession(new ModelResource(uri));
-
- }
- catch (URISyntaxException uriException) {
-
- //this will be caught below
- throw new QueryException("Could not connect to model's Server.",
- uriException);
- }
- }
- else {
-
- // log that we're backing up a server
- if (logger.isDebugEnabled()) {
-
- logger.debug("Backing up server " + sourceURI );
- }
-
- //source is a server.
- setServerURI(sourceURI);
- }
- }
-
-
- /**
- * Try to recognise a uri alias, and return the canonical form instead.
- *
- * @param uri The URI being checked.
- * @return The updated URI. May be the same as the uri parameter.
- */
- private URI getCanonicalUriAlias(URI uri) {
- // only do this for remote protocols
- if (!"rmi".equals(uri.getScheme()) && !"soap".equals(uri.getScheme())) {
- return uri;
- }
- logger.debug("Checking for an alias on: " + uri);
- // extract the host name
- String host = uri.getHost();
- if (host == null) {
- return uri;
- }
- Set hostnames = getHostnameAliases();
- // Check with a DNS server to see if this host is recognised
- InetAddress addr = null;
- try {
- addr = InetAddress.getByName(host);
- } catch (UnknownHostException uhe) {
- // The host was unknown, so allow resolution to continue as before
- return uri;
- }
- // check the various names against known aliases and the given name
- if (
- hostnames.contains(host) ||
- hostnames.contains(addr.getHostName()) ||
- hostnames.contains(addr.getCanonicalHostName()) ||
- hostnames.contains(addr.getHostAddress())
- ) {
- // change the host name to one that is recognised
- // use the system uri to find the local host name
- URI serverURI = getServerURI();
- if (serverURI == null) {
- return uri;
- }
- String newHost = serverURI.getHost();
- try {
- return new URI(uri.getScheme(), newHost, uri.getPath(), uri.getFragment());
- } catch (URISyntaxException e) { /* fall through */ }
- }
-
- // not found, so return nothing
- return uri;
- }
-
-
- /**
- * Method to ask the ServerInfo for the local server aliases.
- * This will return an empty set if ServerInfo is not available -
- * ie. being run on a host which has no local database, such an an iTQL client.
- *
- * @return The set of server aliases as strings
- */
- private static Set getHostnameAliases() {
- Set names = (Set)getServerInfoProperty("HostnameAliases");
- return (names == null) ? java.util.Collections.EMPTY_SET : names;
- }
-
-
- /**
- * Method to ask the ServerInfo for the local server URI.
- * This will return null if ServerInfo is not available -
- * ie. being run on a host which has no local database, such an an iTQL client.
- *
- * @return The URI of the local server, or null if this is not a server.
- */
- private static URI getServerURI() {
- return (URI)getServerInfoProperty("ServerURI");
- }
-
-
- /**
- * Method to get the value of a property from the ServerInfo for the local database session.
- * This will return null if ServerInfo is not available -
- * ie. being run on a host which has no local database, such an an iTQL client.
- *
- * @param property The property to return, with the correct case.
- * @return The object returned from the accessor method named, or null if ServerInfo is not available.
- */
- private static Object getServerInfoProperty(String property) {
- Object o = null;
- try {
- Class rsf = Class.forName("org.mulgara.server.ServerInfo");
- java.lang.reflect.Method getter = rsf.getMethod("get" + property, null);
- o = getter.invoke(null, null);
- } catch (Exception e) { /* no op */ }
- return o;
- }
-
-}
Deleted: branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java
===================================================================
--- branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java 2007-10-23 03:33:36 UTC (rev 494)
+++ branches/nw-interface/src/jar/itql/java/org/mulgara/itql/ItqlInterpreterUnitTest.java 2007-10-24 15:03:08 UTC (rev 495)
@@ -1,2441 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public License
- * Version 1.1 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- *
- * The Original Code is the Kowari Metadata Store.
- *
- * The Initial Developer of the Original Code is Plugged In Software Pty
- * Ltd (http://www.pisoftware.com, mailto:info at pisoftware.com). Portions
- * created by Plugged In Software Pty Ltd are Copyright (C) 2001,2002
- * Plugged In Software Pty Ltd. All Rights Reserved.
- *
- * Contributor(s): N/A.
- *
- * [NOTE: The text of this Exhibit A may differ slightly from the text
- * of the notices in the Source Code files of the Original Code. You
- * should use the text of this Exhibit A rather than the text found in the
- * Original Code Source Code for Your Modifications.]
- *
- */
-
-package org.mulgara.itql;
-
-// third party packages
-import junit.framework.*;
-
-// Java 2 standard packages
-import java.io.*;
-import java.net.*;
-import java.sql.ResultSet;
-import java.util.*;
-import java.rmi.server.UnicastRemoteObject;
-
-import javax.xml.parsers.*;
-
-import org.apache.log4j.Category;
-import org.apache.log4j.xml.DOMConfigurator;
-
-// automagically generated classes
-import org.mulgara.itql.parser.ParserException;
-import org.mulgara.parser.MulgaraParserException;
-import org.mulgara.query.Answer;
-import org.mulgara.query.AnswerImpl;
-import org.mulgara.query.Constraint;
-import org.mulgara.query.ConstraintExpression;
-import org.mulgara.query.ConstraintHaving;
-import org.mulgara.query.ConstraintImpl;
-import org.mulgara.query.ConstraintOccurs;
-import org.mulgara.query.ModelExpression;
-import org.mulgara.query.ModelResource;
-import org.mulgara.query.Order;
-import org.mulgara.query.Query;
-import org.mulgara.query.UnconstrainedAnswer;
-import org.mulgara.query.Variable;
-import org.mulgara.query.rdf.LiteralImpl;
-import org.mulgara.query.rdf.URIReferenceImpl;
-import org.mulgara.util.ResultSetRow;
-import org.mulgara.util.TempDir;
-import org.mulgara.util.TestResultSet;
-
-// emory util package
-import edu.emory.mathcs.util.remote.io.*;
-import edu.emory.mathcs.util.remote.io.server.impl.*;
-
-/**
- * Unit test for {@link ItqlInterpreterUnitTest}. <p>
- *
- * Note. Constraint disjunctions have not yet been implemented, so for now will
- * give the same answers as conjunctions. Hence test results will be <strong>
- * WRONG</strong> once disjunctions are implemented. </p>
- *
- * @created 2001-08-27
- *
- * @author Tom Adams
- *
- * @version $Revision: 1.11 $
- *
- * @modified $Date: 2005/06/26 12:48:09 $ by $Author: pgearon $
- *
- * @company <a href="mailto:info at PIsoftware.com">Plugged In Software</a>
- *
- * @copyright ©2001 <a href="http://www.pisoftware.com/">Plugged In
- * Software Pty Ltd</a>
- *
- * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- */
-public class ItqlInterpreterUnitTest extends TestCase {
-
- //
- // Members
- //
-
- /**
- * the category to send logging info to
- */
- private static Category log =
- Category.getInstance(ItqlInterpreterUnitTest.class.getName());
-
- /**
- * Get line separator.
- */
- private static final String eol = System.getProperty("line.separator");
-
- /**
- * Schema namespace.
- */
- private static final String rdfSchemaNamespace =
- "http://www.w3.org/2000/01/rdf-schema#";
-
- /**
- * the ITQL command interpreter
- */
- private static ItqlInterpreter interpreter = null;
-
- /**
- * the URI of the dublin core schema
- */
- private static URI dcSchemaURI = null;
-
- /**
- * an example model
- */
- private static String testModel = null;
-
- /**
- * a temp directory location
- */
- private static final File tmpDirectory = TempDir.getTempDir();
-
- /**
- * host name of server
- */
- private static String hostName = System.getProperty("host.name");
-
- /**
- * Server1
- */
- private static String server = "rmi://"+hostName+"/server1";
-
- //
- // Public API
- //
-
- /**
- * Constructs a new ItqlInterpreter unit test.
- *
- * @param name the name of the test
- */
- public ItqlInterpreterUnitTest(String name) {
-
- // delegate to super class constructor
- super(name);
-
- // load the logging configuration
- try {
-
- DOMConfigurator.configure(System.getProperty("cvs.root") +
- "/log4j-conf.xml");
- }
- catch (FactoryConfigurationError fce) {
-
- log.error("Unable to configure logging service from XML configuration " +
- "file");
- }
-
- // try-catch
- }
-
- // setUp()
-
- /**
- * Returns a test suite containing the tests to be run.
- *
- * @return the test suite
- */
- public static TestSuite suite() {
-
- TestSuite suite = new TestSuite();
-
- suite.addTest(new ItqlInterpreterUnitTest("testHelp"));
- suite.addTest(new ItqlInterpreterUnitTest("testQuit"));
- suite.addTest(new ItqlInterpreterUnitTest("testSu1"));
- suite.addTest(new ItqlInterpreterUnitTest("testAlias1"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testSelect1"));
- suite.addTest(new ItqlInterpreterUnitTest("testSelect2"));
- suite.addTest(new ItqlInterpreterUnitTest("testSelect3"));
- suite.addTest(new ItqlInterpreterUnitTest("testSelect4"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testSelect5"));
- suite.addTest(new ItqlInterpreterUnitTest("testSelect6"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testSelect7"));
- suite.addTest(new ItqlInterpreterUnitTest("testSelect8"));
- suite.addTest(new ItqlInterpreterUnitTest("testDirectory1"));
- suite.addTest(new ItqlInterpreterUnitTest("testCreate1"));
- suite.addTest(new ItqlInterpreterUnitTest("testDrop1"));
- suite.addTest(new ItqlInterpreterUnitTest("testDelete1"));
- suite.addTest(new ItqlInterpreterUnitTest("testDelete2"));
- suite.addTest(new ItqlInterpreterUnitTest("testInsert1"));
- suite.addTest(new ItqlInterpreterUnitTest("testInsert2"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad1"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad2"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad3"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad4"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad5"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad6"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad7"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad8"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoad9"));
- suite.addTest(new ItqlInterpreterUnitTest("testSet1"));
- suite.addTest(new ItqlInterpreterUnitTest("testSet2"));
- suite.addTest(new ItqlInterpreterUnitTest("test1ParseQuery"));
- suite.addTest(new ItqlInterpreterUnitTest("test2ParseQuery"));
- suite.addTest(new ItqlInterpreterUnitTest("test3ParseQuery"));
- suite.addTest(new ItqlInterpreterUnitTest("test4ParseQuery"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testBackup1"));
- suite.addTest(new ItqlInterpreterUnitTest("testRestore1"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testCreate3"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoadApi1"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoadApi2"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoadApi3"));
- suite.addTest(new ItqlInterpreterUnitTest("testLoadApi4"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testBackupApi1"));
- suite.addTest(new ItqlInterpreterUnitTest("testBackupApi2"));
- suite.addTest(new ItqlInterpreterUnitTest("testBackupApi3"));
- suite.addTest(new ItqlInterpreterUnitTest("testBackupApi4"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testLoadBackupApi1"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testRestoreApi1"));
- suite.addTest(new ItqlInterpreterUnitTest("testRestoreApi2"));
- suite.addTest(new ItqlInterpreterUnitTest("testRestoreApi3"));
-
- suite.addTest(new ItqlInterpreterUnitTest("testBackupRestore1"));
- suite.addTest(new ItqlInterpreterUnitTest("testBackupRestore2"));
- suite.addTest(new ItqlInterpreterUnitTest("testBackupRestore3"));
-
- return suite;
- }
-
- /**
- * Default text runner.
- *
- * @param args the command line arguments
- */
- public static void main(String[] args) {
-
- junit.textui.TestRunner.run(suite());
- }
-
- // suite()
- //
- // Test cases
- //
-
- /**
- * Test the interpreter using a help statement. Executes the following query:
- * <pre>
- * help ;
- * </pre> Expects results: <pre>
- *
- * Valid commands are:
- *
- * su authenticate a user
- * set set a property
- * execute execute an iTQL script
- * alias define an alias
- * create create a model
- * commit commits a transaction
- * drop drop an entire resource
- * insert insert a set of triples
- * delete delete a set of triples
- * load load contents of a file
- * backup backup the contents of a server to a file
- * restore restore a server from a backup file
- * rollback rolls back a transaction
- * select perform a query
- * set sets various options
- * quit end the ITQL session
- * help display this help screen
- *
- * You can also get detailed help on each command:
- *
- * $ help <command> ;
- *
- * For example, to display help on the select command:
- *
- * $ help select ;
- *
- * Note. All commands must be terminated with ";".
- *
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testHelp() throws Exception {
-
- // log that we're executing the test
- log.info("Starting help test");
-
- // create the statement
- String statement = "help ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
-
- String results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- StringBuffer expected = new StringBuffer();
- expected.append(eol + "Valid commands are:" + eol + eol);
- expected.append(" su authenticate a user" + eol);
- expected.append(" set set a property" + eol);
- expected.append(" execute execute an iTQL script" + eol);
- expected.append(" alias define an alias" + eol);
- expected.append(" create create a model" + eol);
- expected.append(" commit commits a transaction" + eol);
- expected.append(" drop drop an entire resource" + eol);
- expected.append(" insert insert a set of triples" + eol);
- expected.append(" delete delete a set of triples" + eol);
- expected.append(" load load contents of a file " + eol);
- expected.append(" backup backup the contents of a server to a file" + eol);
- expected.append(" restore restore a server from a backup file" + eol);
- expected.append(" rollback rolls back a transaction" + eol);
- expected.append(" select perform a query" + eol);
- expected.append(" set sets various options" + eol);
- expected.append(" apply applies a set of rules" + eol);
- expected.append(" quit end the ITQL session" + eol);
- expected.append(" help display this help screen" + eol + eol);
- expected.append("You can also get detailed help on each command:" + eol + eol);
- expected.append(" $ help <command> ;" + eol + eol);
- expected.append("For example, to display help on the select command:" + eol + eol);
- expected.append(" $ help select ;" + eol + eol);
- expected.append("Note. All commands must be terminated with \";\"." + eol);
-
- // check that the result are what we expected
- assertEquals(expected.toString(), results);
-
- // log that we've completed the test
- log.info("Completed help test");
- }
-
- /**
- * Test the interpreter using an insert statement. Executes the following query:
- * <pre>
- * insert $s $p $o into <rmi://localhost/database#model> ;
- * </pre> Expects results: ParserException
- *
- * @throws Exception if the test fails
- */
- public void testInsert1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting insert test 1");
-
- String statement;
-
- // create the statement
- statement = "insert $s $p $o into <file://foo/bar.txt> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- String expected = "Could not insert statements into file://foo/bar.txt" +
- eol + "Predicate must be a valid URI";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed insert test 1");
- }
-
- /**
- * Test the interpreter using an insert statement. Executes the following query:
- * <pre>
- * insert $s <urn:foo:bar> $o into <rmi://localhost/database#model> ;
- * </pre> Expects results: 1 inserted statements with the subject and object
- * as a new blank node each and a fixed predicate.
- *
- * @throws Exception if the test fails
- */
- public void testInsert2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting insert test 1");
-
- String statement;
-
- // create the statement
- statement = "create <rmi://localhost/server1#database> ; " + eol +
- "insert $s <urn:foo:bar> $o into <rmi://localhost/server1#database> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- String expected = "Successfully inserted statements into rmi://localhost/server1#database";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log the results
- log.debug("Received results : " + results);
-
- statement = "drop <rmi://localhost/server1#database> ;";
- interpreter.executeCommand(statement);
-
- // log that we've completed the test
- log.info("Completed insert test 2");
- }
-
- // testHelp()
-
- /**
- * Test the interpreter using a quit statement. Executes the following query:
- * <pre>
- * quit ;
- * </pre> Expects results: <pre>
- * Quitting ITQL session
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testQuit() throws Exception {
-
- // log that we're executing the test
- log.info("Starting quit test");
-
- // create the statement
- String statement = "quit ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
-
- String results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- String expected = "Quitting ITQL session";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log that we've completed the test
- log.info("Completed quit test");
- }
-
- // testQuit()
-
- /**
- * Test the interpreter using an su statement. Executes the following query:
- * <pre>
- * su fred Fo0B at r ;
- * </pre> Expects results: <pre>
- * su is not currently implemented
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSu1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting su test 1");
-
- // create the statement
- String statement = "su <ldap://bar.org> fred Fo0Bar ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
-
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- String expected = "Credential presented";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log that we've completed the test
- log.info("Completed su test 1");
- }
-
- // testSu1()
-
- /**
- * Test the interpreter using an alias statement. Executes the following
- * query: <pre>
- * alias <http://purl.org/dc/elements/1.1> as dc;
- * </pre> Expects results: <pre>
- * Successfully aliased http://purl.org/dc/elements/1.1 as dc
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testAlias1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting alias test 1");
-
- // create the statement
- String statement = "alias <http://purl.org/dc/elements/1.1> as dc ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- String results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- String expected =
- "Successfully aliased http://purl.org/dc/elements/1.1 " + "as dc";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log that we've completed the test
- log.info("Completed alias test 1");
- }
-
- // testAlias1()
-
- /**
- * Test the interpreter using a select statement. Executes the following
- * query: <pre>
- * select $x from <file:<it>mulgarahome</it> /data/dc.rdfs> where $x
- * <http://www.w3.org/2000/01/rdf-schema#label> 'Title' ; </pre> Expects
- * results: <pre>
- * x=http://purl.org/dc/elements/1.1/title
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 1");
-
- // create the statement
- String statement =
- "select $x from <" + dcSchemaURI + "> where $x <" + rdfSchemaNamespace +
- "label> 'Title' ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = new AnswerImpl(interpreter.getLastAnswer());
-
- // log the results
- if (log.isDebugEnabled()) {
- log.debug("Received results : " + results);
- }
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x", new URIReferenceImpl(new URI(
- "http://purl.org/dc/elements/1.1/title")));
-
- Answer expected = new AnswerImpl(trs);
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 1");
- }
-
- // testSelect1()
-
- /**
- * Test the interpreter using a select statement. Executes the following
- * query: <pre>
- * select $x from <file:<it>mulgarahome</it> /data/dc.rdfs> where ($x
- * <http://www.w3.org/2000/01/rdf-schema#label> 'Title') ; </pre>
- * Expects results: <pre>
- * x=http://purl.org/dc/elements/1.1/title
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 2");
-
- // create the statement
- String statement =
- "select $x from <" + dcSchemaURI + "> where ($x <" +
- rdfSchemaNamespace + "label> 'Title') ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = interpreter.getLastAnswer();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x", new URIReferenceImpl(new URI(
- "http://purl.org/dc/elements/1.1/title")));
-
- Answer expected = new AnswerImpl(trs);
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 2");
- }
-
- // testSelect2()
-
- /**
- * Test the interpreter using a select statement. Executes the following
- * query: <pre>
- * select $x $y from <file:<it>mulgarahome</it> /data/dc.rdfs> where ($x
- * $y 'Subject'); </pre> Expects results: <pre>
- * x=http://purl.org/dc/elements/1.1/subject
- * y=http://www.w3.org/2000/01/rdf-schema#label
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect3() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 3");
-
- // create the statement
- String statement =
- "select $x $y from <" + dcSchemaURI + "> where ($x $y 'Subject') ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = interpreter.getLastAnswer();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x",
- new URIReferenceImpl(new URI(
- "http://purl.org/dc/elements/1.1/subject")));
- row.setObject("y",
- new URIReferenceImpl(new URI(
- "http://www.w3.org/2000/01/rdf-schema#label")));
-
- Answer expected = new AnswerImpl(trs);
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 3");
- }
-
- // testSelect3()
-
- /**
- * Test the interpreter using a select statement. Executes the following
- * query: <pre>
- * select $x $y from <file:<it>mulgarahome</it> /data/dc.rdfs> where (($x
- * $y 'Subject') and ($x <http://www.w3.org/2000/01/rdf-schema#label>
- * 'Subject')) ; </pre> Expects results: <pre>
- * x=http://purl.org/dc/elements/1.1/subject
- * y=http://www.w3.org/2000/01/rdf-schema#label
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect4() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 4");
-
- // create the statement
- String statement =
- "select $x $y from <" + dcSchemaURI +
- "> where (($x $y 'Subject') and ($x <" + rdfSchemaNamespace +
- "label> 'Subject')) ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = interpreter.getLastAnswer();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x", new URIReferenceImpl(
- new URI("http://purl.org/dc/elements/1.1/subject")));
- row.setObject("y", new URIReferenceImpl(new URI(
- "http://www.w3.org/2000/01/rdf-schema#label")));
-
- Answer expected = new AnswerImpl(trs);
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 4");
- }
-
- // testSelect4()
-
- /**
- * Test the interpreter using a select statement. Executes the following
- * query: <pre>
- * select $x $y from <file:<it>mulgarahome</it> /data/dc.rdfs> where (($x
- * $y 'Subject') or ($x <http://www.w3.org/2000/01/rdf-schema#label>
- * 'Subject')) ; </pre> Expects results: <pre>
- * x=http://purl.org/dc/elements/1.1/subject
- * y=http://www.w3.org/2000/01/rdf-schema#label
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect5() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 5");
-
- // create the statement
- String statement =
- "select $x $y from <" + dcSchemaURI +
- "> where (($x $y 'Subject') or ($x <" + rdfSchemaNamespace +
- "label> 'Subject')) ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = new AnswerImpl(interpreter.getLastAnswer());
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x", new URIReferenceImpl(new URI(
- "http://purl.org/dc/elements/1.1/subject")));
- row.setObject("y", null);
- row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x", new URIReferenceImpl(new URI(
- "http://purl.org/dc/elements/1.1/subject")));
- row.setObject("y", new URIReferenceImpl(new URI(
- "http://www.w3.org/2000/01/rdf-schema#label")));
-
- Answer expected = new AnswerImpl(trs);
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 5");
- }
-
- // testSelect5()
-
- /**
- * Test the interpreter using a select statement. Executes the following
- * query: <pre>
- * select $x $y from <file:<it>mulgarahome</it> /data/dc.rdfs> where (($x $y
- * 'Subject') and ($x <http://www.w3.org/2000/01/rdf-schema#label>
- * 'Subject')) and <http://purl.org/dc/elements/1.1/subject> $y
- * 'Subject' ; </pre> Expects results: <pre>
- * x=http://purl.org/dc/elements/1.1/subject
- * y=http://www.w3.org/2000/01/rdf-schema#label
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect6() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 6");
-
- // create the statement
- String statement =
- "select $x $y from <" + dcSchemaURI +
- "> where (($x $y 'Subject') and ($x <" + rdfSchemaNamespace +
- "label> 'Subject'))" +
- "and <http://purl.org/dc/elements/1.1/subject> $y 'Subject' ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = interpreter.getLastAnswer();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x",
- new URIReferenceImpl(new URI(
- "http://purl.org/dc/elements/1.1/subject")));
- row.setObject("y",
- new URIReferenceImpl(new URI(
- "http://www.w3.org/2000/01/rdf-schema#label")));
-
- Answer expected = new AnswerImpl(trs);
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 6");
- }
-
- // testSelect6()
-
- /**
- * Test the interpreter using a select statement. Executes the following
- * query: <pre>
- * select $x $y from <file:<it>mulgarahome</it> /data/dc.rdfs> where (($x
- * $y 'Subject') and ($x <http://www.w3.org/2000/01/rdf-schema#label>
- * 'Subject')) or <http://purl.org/dc/elements/1.1/subject> $y 'Subject'
- * ; </pre> Expects results: <pre>
- * x=http://purl.org/dc/elements/1.1/subject
- * y=http://www.w3.org/2000/01/rdf-schema#label
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect7() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 7");
-
- // create the statement
- String statement =
- "select $x $y from <" + dcSchemaURI +
- "> where (($x $y 'Subject') and ($x <" + rdfSchemaNamespace +
- "label> 'Subject'))" +
- "or <http://purl.org/dc/elements/1.1/subject> $y 'Subject' ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = interpreter.getLastAnswer();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x", "y"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x",
- new URIReferenceImpl(new URI(
- "http://purl.org/dc/elements/1.1/subject")));
- row.setObject("y",
- new URIReferenceImpl(new URI(
- "http://www.w3.org/2000/01/rdf-schema#label")));
-
- Answer expected = new AnswerImpl(trs);
-/*
- expected.beforeFirst();
- results.beforeFirst();
- while (true) {
- boolean expN = expected.next();
- boolean resN = results.next();
- if (expN && resN) {
- log.warn("exp x = " + expected.getObject("x") + " exp y = " + expected.getObject("y") +
- " res x = " + results.getObject("x") + " res y = " + results.getObject("y"));
- } else if (!expN && !resN) {
- log.warn("Finished dumping results");
- break;
- } else if (resN) {
- do {
- log.warn("extra result: res x = " + results.getObject("x") + " res y = " + results.getObject("y"));
- } while (results.next());
- } else {
- log.warn("expN = " + expN + " resN = " + resN);
- break;
- }
- }
-*/
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 7");
- }
-
- // testSelect7()
-
- /**
- * Test the interpreter using a select statement with a count and a having.
- * Executes the following query: <pre>
- * select count (
- * select $x $y
- * from <file:<it>mulgarahome</it> /data/dc.rdfs>
- * where (($x $y 'Subject') and ($x <http://www.w3.org/2000/01/rdf-schema#label> 'Subject'))
- * from <file:<it>mulgarahome</it> /data/dc.rdfs>
- * where (($x $y 'Subject') and ($x <http://www.w3.org/2000/01/rdf-schema#label> 'Subject')) ;
- * </pre> Expects results: <pre>
- * k0=http://purl.org/dc/elements/1.1/subject
- * y=http://www.w3.org/2000/01/rdf-schema#label
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSelect8() throws Exception {
-
- // log that we're executing the test
- log.info("Starting select test 8");
-
- // create the statement
- String statement =
- "select $x $y count ( " +
- " select $x $y " +
- " from <" + dcSchemaURI + "> " +
- " where (($x $y 'Subject') " +
- " and ($x <" + rdfSchemaNamespace + "label> 'Subject'))) " +
- "from <" + dcSchemaURI + "> " +
- "where (($x $y 'Subject') " +
- "and ($x <" + rdfSchemaNamespace + "label> 'Subject')) " +
- "having $k0 <http://mulgara.org/mulgara#occurs> '1.0'^^<http://www.w3.org/2001/XMLSchema#double> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- Answer results = new AnswerImpl(interpreter.getLastAnswer());
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose the expected result
- TestResultSet trs = new TestResultSet(new String[] {"x", "y", "k0"});
- ResultSetRow row = new ResultSetRow(trs);
- trs.addRow(row);
- row.setObject("x", new URIReferenceImpl(
- new URI("http://purl.org/dc/elements/1.1/subject")));
- row.setObject("y", new URIReferenceImpl(
- new URI("http://www.w3.org/2000/01/rdf-schema#label")));
- row.setObject("k0", new LiteralImpl(1.0d));
-
- Answer expected = new AnswerImpl(trs);
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- results.close();
- expected.close();
-
- // log that we've completed the test
- log.info("Completed select test 7");
- }
-
- // testSelect8()
-
- /**
- * Test the interpreter using a delete statement. Executes the following query:
- * <pre>
- * delete $s $p $o from <rmi://localhost/database#model> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testDelete1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting delete test 1");
-
- String statement;
-
- // create the statement
- statement = "delete $s $p $o from <file://foo/bar.txt> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- String expected = "Could not delete statements from file://foo/bar.txt" +
- eol + "Predicate must be a valid URI";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed drop test 1");
- }
-
- /**
- * Test the interpreter using a delete statement. Executes the following query:
- * <pre>
- * delete $s <urn:foo:bar> $o from <rmi://localhost/database#model> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testDelete2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting delete test 2");
-
- String statement;
-
- // create the statement
- statement = "delete $s <urn:foo:bar> $o from <file://foo/bar.txt> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- String expected = "Could not delete statements from file://foo/bar.txt" +
- eol + "Cannot use variables when deleting statements";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed drop test 2");
- }
-
- /**
- * Test the interpreter using a directory statement. Executes the following
- * query: <pre>
- * directory <beep://rns.site1.net:7000/models> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testDirectory1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting directory DB test 1");
-
- // create the statement
- String statement = "directory <beep://rns.site1.net:7000/models> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed directory test 1");
- }
-
- // testDirectory1()
-
- /**
- * Test the interpreter using a create statement. Executes the following
- * query: <pre>
- * create <mulgara://localhost/database> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testCreate1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting create test 1");
-
- // create the statement
- String statement = "create <mulgara://localhost/database> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed create test 1");
- }
-
- // testCreate1()
-
- /**
- * Test the interpreter using a create statement. Executes the following
- * query: <pre>
- * create <mulgara://localhost/database#model> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testCreate2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting create test 2");
-
- // create the statement
- String statement = "create <mulgara://localhost/database#model> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed create test 2");
- }
-
- // testCreate2()
-
- /**
- * Test the interpreter using a drop statement. Executes the following query:
- * <pre>
- * drop <mulgara://localhost/database#model> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testDrop1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting drop test 1");
-
- // create the statement
- String statement = "drop <mulgara://localhost/database> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed drop test 1");
- }
-
- // testDrop1()
-
- /**
- * Test the interpreter using a drop statement. Executes the following query:
- * <pre>
- * drop <mulgara://localhost/database#model> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testDrop2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting drop test 2");
-
- // create the statement
- String statement = "drop <mulgara://localhost/database#model> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed drop test 2");
- }
-
- // testDrop2()
- // Proposed tests
- //
- //insert unbraced triple into database
- //insert unbraced triple into model
- //insert braced triple into database
- //insert braced triple into model
- //insert unbraced database into database
- //insert unbraced database into model
- //insert unbraced model into database
- //insert unbraced model into model
- //insert braced database into database
- //insert braced database into model
- //insert braced model into database
- //insert braced model into model
- //insert unbraced select into database
- //insert unbraced select into model
- //insert braced select into database
- //insert braced select into model
- // insert 'title' 'title' 'title' into rmi://localhost/server1#insert ;
- // -> this is a bad triple as it contains a literal as it's subject and predicate
- //
- // alias http://www.w3.org/2000/01/rdf-schema# as rdfs ;
- // insert http://purl.org/dc/elements/1.1/language rdfs:label 'Language' into rmi://localhost/server1#insert ;
- //
- // or equivalently
- //
- // insert http://purl.org/dc/elements/1.1/language http://www.w3.org/2000/01/rdf-schema#label 'Language' into rmi://localhost/server1#insert ;
- //
- // iTQL> create rmi://localhost/server1#foo ;
- // Successfully created model rmi://localhost/server1#foo
- // iTQL> select $x $y $z from rmi://localhost/server1#foo where $x $y $x ;
- // 2 columns: x y (0 rows)
- // iTQL> insert http://purl.org/dc/elements/1.1/title http://www.w3.org/2000/01/rdf-schema#label 'Title' into rmi://localhost/server1#foo ;
- // Successfully inserted statements into rmi://localhost/server1#foo
- // iTQL> select $x $y $z from rmi://localhost/server1#foo where $x $y $x ;
- // 2 columns: x y (1 rows)
- // x="Title" y=http://www.w3.org/2000/01/rdf-schema#label
- // iTQL> drop rmi://localhost/server1#foo ;
- // Successfully dropped model rmi://localhost/server1#foo
- // Proposed tests
- //
- //delete unbraced triple into database
- //delete unbraced triple into model
- //delete braced triple into database
- //delete braced triple into model
- //delete unbraced database into database
- //delete unbraced database into model
- //delete unbraced model into database
- //delete unbraced model into model
- //delete braced database into database
- //delete braced database into model
- //delete braced model into database
- //delete braced model into model
- //delete unbraced select into database
- //delete unbraced select into model
- //delete braced select into database
- //delete braced select into model
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load <http://purl.org/dc/elements/1.1> into
- * <mulgara://localhost/database#model> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 1");
-
- // create the statement
- String statement =
- "load <http://purl.org/dc/elements/1.1> into <" + testModel + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 1");
- }
-
- // testLoad1()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load <file:<it>mulgarahome</it> /data/dc.rdfs> into
- * <mulgara://localhost/database> ; </pre> Expects results:
- * MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 2");
-
- // create the statement
- String statement =
- "load <" + dcSchemaURI + "> into <" + server + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 2");
- }
-
- // testLoad2()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load <file:<it>mulgarahome</it> /data/dc.rdfs> into
- * <mulgara://localhost/database#model> ; </pre> Expects results:
- * MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad3() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 3");
-
- // create the statement
- String statement = "load <" + dcSchemaURI + "> into <" + testModel + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 3");
- }
-
- // testLoad3()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load as rdf <http://<it>dchost</it> /<it>path</it> /dc.rdfs> into
- * <mulgara://localhost/database#model> ; </pre> Expects results:
- * MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad4() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 4");
-
- // create the statement
- String statement =
- "load <http://purl.org/dc/elements/1.1> into <" + testModel + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 4");
- }
-
- // testLoad4()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load as rdf <file:<it>mulgarahome</it> /data/dc.rdfs> into
- * <mulgara://localhost/database> ; </pre> Expects results:
- * MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad5() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 5");
-
- // create the statement
- String statement =
- "load <" + dcSchemaURI + "> into <" + server + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 5");
- }
-
- // testLoad5()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load as rdf <file:<it>mulgarahome</it> /data/dc.rdfs> into
- * <mulgara://localhost/database#model> ; </pre> Expects results:
- * MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad6() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 6");
-
- // create the statement
- String statement =
- "load <" + dcSchemaURI + "> into <" + testModel + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 6");
- }
-
- // testLoad6()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load as serial <http://<it>dchost</it> /<it>path</it> /<it>database
- * </it>> into <mulgara://localhost/database#model> ; </pre> Expects
- * results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad7() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 7");
-
- // create the statement
- String statement =
- "load <http://purl.org/dc/elements/1.1> into <" + testModel +
- "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 7");
- }
-
- // testLoad7()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load as serial <file:<it>mulgarahome</it> /data/<it>database</it> >
- * into <mulgara://localhost/database> ; </pre> Expects results:
- * MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad8() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 8");
-
- // create the statement
- String statement =
- "load <" + dcSchemaURI + "> into <" + server + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 8");
- }
-
- // testLoad8()
-
- /**
- * Test the interpreter using a load statement. Executes the following query:
- * <pre>
- * load as serial <file:<it>mulgarahome</it> /<it>database</it> > into
- * <mulgara://localhost/database#model> ; </pre> Expects results:
- * MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testLoad9() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load test 9");
-
- // create the statement
- String statement =
- "load <" + dcSchemaURI + "> into <" + testModel + "> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed load test 9");
- }
-
- // testLoad9()
- // Proposed tests
- //
- //dump unbraced triple into file:<filename>
- //dump braced triple into file:<filename>
- //dump unbraced database into file:<filename>
- //dump unbraced model into file:<filename>
- //dump braced database into file:<filename>
- //dump braced model into file:<filename>
- //dump unbraced select into file:<filename>
- //dump braced select into file:<filename>
- //dump unbraced triple into file:<filename> as rdf
- //dump braced triple into file:<filename> as rdf
- //dump unbraced database into file:<filename> as rdf
- //dump unbraced model into file:<filename> as rdf
- //dump braced database into file:<filename> as rdf
- //dump braced model into file:<filename> as rdf
- //dump unbraced select into file:<filename> as rdf
- //dump braced select into file:<filename> as rdf
- //dump unbraced triple into file:<filename> as serial
- //dump braced triple into file:<filename> as serial
- //dump unbraced database into file:<filename> as serial
- //dump unbraced model into file:<filename> as serial
- //dump braced database into file:<filename> as serial
- //dump braced model into file:<filename> as serial
- //dump unbraced select into file:<filename> as serial
- //dump braced select into file:<filename> as serial
-
- /**
- * Test the interpreter using a set statement. Executes the following query:
- * <pre>
- * set time on ;
- * </pre> Expects results: <pre>
- * Command timing on
- * Command execution time - XXX.XXX seconds
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSet1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting set test 1");
-
- // create the statement
- String statement = "set time on ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- String results;
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose expected result
- String expected = "Command timing is on" + eol + "Command execution time - ";
-
- // check that the result are what we expected (we cannot know the
- // execution time)
- assertEquals(true, results.startsWith(expected));
-
- // log that we've completed the test
- log.info("Completed set test 1");
- }
-
- // testSet1()
-
- /**
- * Test the interpreter using a set statement. Executes the following query:
- * <pre>
- * set time off ;
- * </pre> Expects results: <pre>
- * Command timing off
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testSet2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting set test 2");
-
- // create the statement
- String statement = "set time off ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- String results;
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // compose expected result
- String expected = "Command timing is off";
-
- // check that the result are what we expected
- assertEquals(expected, results);
-
- // log that we've completed the test
- log.info("Completed set test 2");
- }
-
- // testSet2()
-
- /**
- * Test the interpreter using a backup statement. Executes the following
- * query: <pre>
- * backup <rmi://localhost/server1> to <file:/tmp/foobackup1.gz> ;
- * </pre> Expects results: <pre>
- * TODO
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testBackup1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting backup test 1");
-
- // create the statement
- File backupFile = new File(tmpDirectory, "server1backup.gz");
- String statement =
- "backup <"+server+"> to <" + backupFile.toURI() + ">;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- String results;
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log that we've completed the test
- log.info("Completed backup test 1");
- }
-
- // testBackup1()
-
- /**
- * Test the interpreter using a restore statement. Executes the following
- * query: <pre>
- * restore <rmi://localhost/server1> from <file:/tmp/foobackup1.gz> ;
- * </pre> Expects results: <pre>
- * TODO
- * </pre>
- *
- * @throws Exception if the test fails
- */
- public void testRestore1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting restore test 1");
-
- // create the statement
- File backupFile = new File(tmpDirectory, "server1backup.gz");
- String statement =
- "restore <"+server+"> from <" + backupFile.toURI() + ">;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- String results;
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log that we've completed the test
- log.info("Completed restore test 1");
- }
-
- // testRestore1()
-
- /**
- * Tests the backup and restore functionality of Mulgara by running a query,
- * backing up the DB, deleting the server.
- *
- * @throws Exception if the test fails
- */
- public void testBackupRestore1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting combined backup-restore test 1");
-
- // TODO - perform the backup
- // create the statement
- File backupFile = new File(tmpDirectory, "server1backup.gz");
- String statement =
- "restore <"+server+"> from <" + backupFile.toURI() + ">;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- String results;
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log that we've completed the test
- log.info("Completed combined backup-restore test 1");
- }
-
- // testBackupRestore1()
-
- /**
- * Tests the backup and restore functionality of Mulgara by running a query,
- * backing up the DB, deleting the server.
- *
- * @throws Exception if the test fails
- */
- public void testBackupRestore2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting combined backup-restore test 2");
-
- // TODO - perform the backup
- // create the statement
- File backupFile = new File(tmpDirectory, "server1backup.gz");
- String statement =
- "restore <"+server+"> from local <" + backupFile.toURI() + ">;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- interpreter.executeCommand(statement);
- interpreter.getLastMessage();
-
- // log that we've completed the test
- log.info("Completed combined backup-restore test 2");
- }
-
- /**
- * Tests the backup and restore functionality of Mulgara by running a query,
- * backing up the DB, deleting the server.
- *
- * @throws Exception if the test fails
- */
- public void testBackupRestore3() throws Exception {
-
- // log that we're executing the test
- log.info("Starting combined backup-restore test 3");
-
- // TODO - perform the backup
- // create the statement
- File backupFile = new File(tmpDirectory, "server1backup.gz");
- String statement =
- "restore <"+server+"> from remote <" + backupFile.toURI() + ">;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- // execute the query
- String results;
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log that we've completed the test
- log.info("Completed combined backup-restore test 3");
- }
-
-
-
- /**
- * Test #1 for {@link ItqlInterpreter#parseQuery}.
- *
- * @throws Exception EXCEPTION TO DO
- */
- @SuppressWarnings("unchecked")
- public void test1ParseQuery() throws Exception {
-
- log.info("Starting parse query 1");
-
- // Compose the expected result
- Query expected = new Query(
- Arrays.asList(new Object[] {
- new Variable("x")}), // variable list
- new ModelResource(new URI("x:m")), // model expression
- new ConstraintImpl(new Variable("x"), // constraint expression
- new URIReferenceImpl(new URI("x:p")),
- new LiteralImpl("o")),
- null, // no having
- (List<Order>)Collections.EMPTY_LIST, // no ordering
- null, // no limit
- 0, // zero offset
- new UnconstrainedAnswer());
-
- // Check that the result is as expected
- assertEquals(expected,
- interpreter.parseQuery(
- "select $x from <x:m> where $x <x:p> 'o';"));
-
- log.info("Completed parse query 1");
- }
-
- /**
- * Test #2 for {@link ItqlInterpreter#parseQuery}. Non-queries should return a
- * {@link MulgaraParserException}.
- *
- * @throws Exception EXCEPTION TO DO
- */
- public void test2ParseQuery() throws Exception {
-
- log.info("Starting parse query 2");
-
- try {
-
- String notAQuery = "quit";
- Query query = interpreter.parseQuery(notAQuery);
- fail("\"" + notAQuery + "\" erroneously parsed as \"" + query + "\"");
- } catch (MulgaraParserException e) {
-
- // this is the correct response
- }
- log.info("Completed parse query 2");
- }
-
- /**
- * Test #3 for {@link ItqlInterpreter#parseQuery}. This tests that the limit
- * and offset can be assigned.
- *
- * @throws Exception EXCEPTION TO DO
- */
- @SuppressWarnings("unchecked")
- public void test3ParseQuery() throws Exception {
-
- log.info("Starting parse query 3");
- // Compose the expected result
- Query expected = new Query(
- Arrays.asList(new Object[] {new Variable("x")}), // variable list
- new ModelResource(new URI("x:m")), // model expression
- new ConstraintImpl(new Variable("x"), // constraint expression
- new URIReferenceImpl(new URI("x:p")),
- new LiteralImpl("o")),
- null, // no having
- (List<Order>)Collections.EMPTY_LIST, // no ordering
- new Integer(10), // limit
- 2, // offset
- new UnconstrainedAnswer());
-
- // Check that the result is as expected
- assertEquals(expected,
- interpreter.parseQuery(
- "select $x from <x:m> where $x <x:p> 'o' limit 10 offset 2;"));
- log.info("Completed parse query 3");
- }
-
- /**
- * Test #3 for {@link ItqlInterpreter#parseQuery}. This tests the having
- * expression.
- *
- * @throws Exception EXCEPTION TO DO
- */
- public void test4ParseQuery() throws Exception {
-
- log.info("Starting parse query 4");
- // Compose the expected result
-
- List varList = Arrays.asList(new Variable[] { new Variable("x") });
- ModelExpression model = new ModelResource(new URI("x:m"));
- ConstraintExpression where = new ConstraintImpl(
- new Variable("x"),
- new URIReferenceImpl(new URI("x:p")),
- new LiteralImpl("o"));
- ConstraintHaving having = new ConstraintOccurs(new Variable("x"),
- new LiteralImpl(2d));
-
- Query expected = new Query(
- varList, // variable list
- model, // model expression
- where, // constraint expression
- having, // a simple having
- Collections.EMPTY_LIST, // no ordering
- new Integer(10), // limit
- 2, // offset
- new UnconstrainedAnswer());
-
- // Check that the result is as expected
- assertEquals(expected, interpreter.parseQuery("select $x from <x:m> " +
- "where $x <x:p> 'o' " +
- "having $x <http://mulgara.org/mulgara#occurs> " +
- "'2.0'^^<http://www.w3.org/2001/XMLSchema#double> limit 10 offset 2;"));
- log.info("Completed parse query 4");
- }
-
- // ItqlInterpreterUnitTest()
- //
- // Test configuration
- //
-
- /**
- * Initialise members.
- *
- * @throws Exception if something goes wrong
- */
- protected void setUp() throws Exception {
-
- // initialise the interpreter if needed
- if (this.interpreter == null) {
-
- /*
- SessionFactory sessionFactory =
- SessionFactoryFinder.newSessionFactory(null);
- */
-
- this.interpreter = new ItqlInterpreter(
- /*
- sessionFactory.newSession(),
- sessionFactory.getSecurityDomain(),
- */
- new HashMap()
- );
- }
-
- // end if
- // initialise the dublin core schema test data if needed
- if (dcSchemaURI == null) {
-
- dcSchemaURI =
- new URI(new File(System.getProperty("cvs.root") + "/data/dc.rdfs").
- toURL()
- .toString());
- }
-
- // end if
- // initialise the test model if needed
- if (testModel == null) {
-
- testModel = server+"#itqlmodel2";
- }
-
- // end if
- }
-
- /**
- * Test the interpreter using a create statement. Executes the following
- * query: <pre>
- * create <mulgara://localhost/database> ;
- * </pre> Expects results: MulgaraParserException
- *
- * @throws Exception if the test fails
- */
- public void testCreate3() throws Exception {
-
- // log that we're executing the test
- log.info("Starting create test 3");
-
- // create the statement
- String statement = "create <"+ testModel +"> ;";
-
- // log the query we'll be sending
- log.debug("Executing statement : " + statement);
-
- String results = "";
-
- // execute the query
- interpreter.executeCommand(statement);
- results = interpreter.getLastMessage();
-
- // log the results
- log.debug("Received results : " + results);
-
- // log that we've completed the test
- log.info("Completed create test 3");
- }
-
- // testCreate1()
-
-
- /**
- * Test the interpreter using a load API remotely .
- *
- * @throws Exception if the test fails
- */
- public void testLoadApi1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load API test 1");
-
- URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
- URI modelURI = new URI(testModel);
-
- // execute the load remotely
- long statements = interpreter.load(null, sourceURI, modelURI);
-
- this.assertEquals("Incorrect number of statements inserted", 146, statements);
- log.info("Completed test load api 1");
- }
-
- // testLoadApi1()
-
- /**
- * Test the interpreter using a load API locally
- *
- * @throws Exception if the test fails
- */
- public void testLoadApi2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load API test 2");
-
- URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
- URI modelURI = new URI(testModel);
-
- // open and wrap the inputstream
- RemoteInputStreamSrvImpl srv =
- new RemoteInputStreamSrvImpl(sourceURI.toURL().openStream());
-
- // prepare it for exporting
- UnicastRemoteObject.exportObject(srv);
-
- RemoteInputStream inputStream = new RemoteInputStream(srv);
-
- // execute the load locally
- long statements = interpreter.load(inputStream,
- sourceURI, modelURI);
-
- this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
- inputStream.close();
-
- log.info("Completed test load api 2");
- }
-
- // testLoadApi2()
-
- /**
- * Test the interpreter using a load API locally
- *
- * @throws Exception if the test fails
- */
- public void testLoadApi3() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load API test 3");
-
- URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
- URI dummyURI = new URI("http://mydummysite.com/rssfeed.rdf");
- URI modelURI = new URI(testModel);
-
- // execute the load locally - pass an invalid URI for the server.
- // This should succeed as the server will ignore the dummyURI
- long statements = interpreter.load(sourceURI.toURL().openStream(),
- dummyURI, modelURI);
-
- this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
- log.info("Completed test load api 3");
- }
-
- /**
- * Test the interpreter using a load API locally
- *
- * @throws Exception if the test fails
- */
- public void testLoadApi4() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load API test 4");
-
- URI sourceURI = new URI("http://purl.org/dc/elements/1.1");
- URI modelURI = new URI(testModel);
-
- // execute the load locally
- long statements = interpreter.load(sourceURI.toURL().openStream(),
- modelURI);
-
- this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
- log.info("Completed test load api 4");
- }
-
- /**
- * Test the interpreter using a backup API remotely .
- *
- * @throws Exception if the test fails
- */
- public void testBackupApi1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting backup API test 1");
-
- File file = new File(tmpDirectory, "backup1.rdf");
- file.delete();
-
- URI modelURI = new URI(testModel);
-
- // execute the backup remotely
- interpreter.backup(modelURI, file);
-
- this.assertTrue("Expected a backup file", file.exists());
- }
-
- // testbackupApi1()
-
- /**
- * Test the interpreter using a backup API locally
- *
- * @throws Exception if the test fails
- */
- public void testBackupApi2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting backup API test 2");
-
- File file = new File(tmpDirectory, "backup2.rdf");
- file.delete();
-
- URI modelURI = new URI(testModel);
-
- // execute the backup remotely
- interpreter.backup(modelURI, new FileOutputStream(file));
-
- this.assertTrue("Expected a backup file", file.exists());
-
- }
-
- // testbackupApi2()
-
- /**
- * Test the interpreter using a backup API locally
- *
- * @throws Exception if the test fails
- */
- public void testBackupApi3() throws Exception {
-
- // log that we're executing the test
- log.info("Starting backup API test 3");
-
- File file = new File(tmpDirectory, "backup1.gz");
- file.delete();
-
- URI serverURI = new URI(server);
-
- // execute the backup locally
- interpreter.backup(serverURI, file);
-
- this.assertTrue("Expected a backup file", file.exists());
-
- }
-
- /**
- * Test the interpreter using a backup API locally
- *
- * @throws Exception if the test fails
- */
- public void testBackupApi4() throws Exception {
-
- // log that we're executing the test
- log.info("Starting backup API test 3");
-
- File file = new File(tmpDirectory, "backup2.gz");
- file.delete();
-
- URI serverURI = new URI(server);
-
- // execute the backup remotely
- interpreter.backup(serverURI, new FileOutputStream(file));
-
- this.assertTrue("Expected a backup file", file.exists());
-
- }
-
- /**
- * Test the interpreter using a Load API locally
- *
- * @throws Exception if the test fails
- */
- public void testLoadBackupApi1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting load a backup API test 1");
-
- File file = new File(tmpDirectory, "backup1.rdf");
-
- URI modelURI = new URI(testModel);
-
- // execute the backup remotely
- long statements = interpreter.load(file.toURL().openStream(), modelURI);
-
- this.assertEquals("Incorrect number of statements inserted", 146, statements);
-
- }
-
-
- /**
- * Test the interpreter using a restore API locally
- *
- * @throws Exception if the test fails
- */
- public void testRestoreApi1() throws Exception {
-
- // log that we're executing the test
- log.info("Starting Restore API test 1");
-
- File file = new File(tmpDirectory, "backup1.gz");
-
- URI serverURI = new URI(server);
-
- // execute the backup remotely
- interpreter.restore(new FileInputStream(file), serverURI);
-
- }
-
- /**
- * Test the interpreter using a restore API remotely
- *
- * @throws Exception if the test fails
- */
- public void testRestoreApi2() throws Exception {
-
- // log that we're executing the test
- log.info("Starting Restore API test 2");
-
- File file = new File(tmpDirectory, "backup1.gz");
-
- URI serverURI = new URI(server);
-
- // execute the backup remotely
- interpreter.restore(null, serverURI, file.toURI());
-
- }
-
- /**
- * Test the interpreter using a restore API locally
- *
- * @throws Exception if the test fails
- */
- public void testRestoreApi3() throws Exception {
-
- // log that we're executing the test
- log.info("Starting Restore API test 3");
-
- File file = new File(tmpDirectory, "backup2.gz");
-
- // provide a not existence file.
- // this should not fail as the input stream is used
- File dummy = new File(tmpDirectory, "dummyfile.gz");
-
- URI serverURI = new URI(server);
-
- // execute the backup remotely
- interpreter.restore(file.toURL().openStream(), serverURI, dummy.toURI());
-
- }
-
-
- // main()
-}
Modified: branches/nw-interface/src/jar/krule/java/org/mulgara/krule/KruleLoader.java
===================================================================
--- branches/nw-interface/src/jar/krule/java/org/mulgara/krule/KruleLoader.java 2007-10-23 03:33:36 UTC (rev 494)
+++ branches/nw-interface/src/jar/krule/java/org/mulgara/krule/KruleLoader.java 2007-10-24 15:03:08 UTC (rev 495)
@@ -69,7 +69,7 @@
private Session session;
/** The interpreter for parsing queries. */
- private ItqlInterpreter interpreter;
+ private TqlInterpreter interpreter;
/** The rules. */
private RuleStructure rules;
@@ -87,19 +87,19 @@
private String prefixModel;
/** A map of namespace names to the URIs. */
- private Map aliases;
+ private Map<String,URI> aliases;
/** Map of krule:URIReference nodes to their associated URIs. */
- private Map uriReferences;
+ private Map<URIReference,URIReference> uriReferences;
/** Map of krule:Variable nodes to their associated nodes. */
- private Map varReferences;
+ private Map<URIReference,Variable> varReferences;
/** Map of krule:Literal nodes to their associated strings. */
- private Map literalReferences;
+ private Map<Node,Literal> literalReferences;
/** Map of Constraint nodes to the associated constraint object. */
- private Map constraintMap;
+ private Map<Node,ConstraintExpression> constraintMap;
/** URI for the Krule namespace. */
private static final String KRULE = "http://mulgara.org/owl/krule/#";
@@ -211,7 +211,7 @@
newAliases();
// initialize the constriant map
- constraintMap = new HashMap();
+ constraintMap = new HashMap<Node,ConstraintExpression>();
}
@@ -241,7 +241,7 @@
this.systemModel = systemModel;
// get a new interpreter
- interpreter = new ItqlInterpreter(session, aliases);
+ interpreter = new TqlInterpreter(aliases);
rules = null;
try {
@@ -400,9 +400,9 @@
private void loadQueries() throws TuplesException, QueryException, KruleStructureException, InitializerException {
logger.debug("Loading Queries");
// go through the rules to set their queries
- Iterator ri = rules.getRuleIterator();
+ Iterator<Rule> ri = rules.getRuleIterator();
while (ri.hasNext()) {
- Rule rule = (Rule)ri.next();
+ Rule rule = ri.next();
logger.debug("Reading query for rule: " + rule.getName());
Query query;
@@ -498,7 +498,7 @@
* @throws KruleStructureException When there is an error in the RDF data structure.
* @throws InitializerException When there is an intialization error.
*/
- private Set findAxioms() throws TuplesException, QueryException, KruleStructureException, InitializerException {
+ private Set<org.jrdf.graph.Triple> findAxioms() throws TuplesException, QueryException, KruleStructureException, InitializerException {
logger.debug("Loading Axioms");
Query query;
@@ -513,7 +513,7 @@
Answer answer = session.query(query);
// prepare the set of axioms
- Set axioms = new HashSet();
+ Set<org.jrdf.graph.Triple> axioms = new HashSet<org.jrdf.graph.Triple>();
try {
Node sn = null;
@@ -557,8 +557,8 @@
*
* @return A map of aliases to their fully qualified names
*/
- private Map newAliases() {
- aliases = new HashMap();
+ private Map<String,URI> newAliases() {
+ aliases = new HashMap<String,URI>();
try {
aliases.put("rdf", new URI("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
aliases.put("rdfs", new URI("http://www.w3.org/2000/01/rdf-schema#"));
@@ -631,7 +631,7 @@
logger.debug("Found all URI references.");
// create the mapping
- uriReferences = new HashMap();
+ uriReferences = new HashMap<URIReference,URIReference>();
// map each reference to the associated URI
try {
while (answer.next()) {
@@ -670,7 +670,7 @@
logger.debug("Found all variable references.");
// create the mapping
- varReferences = new HashMap();
+ varReferences = new HashMap<URIReference,Variable>();
try {
// map each reference to the associated variable
while (answer.next()) {
@@ -709,7 +709,7 @@
logger.debug("Found all Literals.");
// create the mapping
- literalReferences = new HashMap();
+ literalReferences = new HashMap<Node,Literal>();
try {
// map each reference to the associated String
while (answer.next()) {
@@ -750,7 +750,7 @@
logger.debug("Found all simple constraints.");
// create a mapping of URIs to simple constraint structures
- Map simpleConstraints = new HashMap();
+ Map<Node,Map<Node,Node>> simpleConstraints = new HashMap<Node,Map<Node,Node>>();
try {
// map each reference to the associated property/values
while (answer.next()) {
@@ -767,19 +767,17 @@
logger.debug("Mapped all constraints to their property/values");
// collect all property/values together into constraints
- Iterator entries = simpleConstraints.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry)entries.next();
+ for (Map.Entry<Node,Map<Node,Node>> entry: simpleConstraints.entrySet()) {
// get the node in question
- Node constraintNode = (Node)entry.getKey();
+ Node constraintNode = entry.getKey();
// get its properties
- Map pv = (Map)entry.getValue();
+ Map<Node,Node> pv = entry.getValue();
// get the individual properties
- ConstraintElement s = convertToElement((Node)pv.get(HAS_SUBJECT));
- ConstraintElement p = convertToElement((Node)pv.get(HAS_PREDICATE));
- ConstraintElement o = convertToElement((Node)pv.get(HAS_OBJECT));
+ ConstraintElement s = convertToElement(pv.get(HAS_SUBJECT));
+ ConstraintElement p = convertToElement(pv.get(HAS_PREDICATE));
+ ConstraintElement o = convertToElement(pv.get(HAS_OBJECT));
// check if there is a "from" property
- Node from = (Node)pv.get(HAS_MODEL);
+ Node from = pv.get(HAS_MODEL);
// build the appropriate constraint
// add it to the map
if (from == null) {
@@ -820,10 +818,10 @@
// accumulate all the constraint links and types
// create a map of join constraints to the constraints that they join
- Map constraintLinks = new HashMap();
+ Map<Node,Set<Node>> constraintLinks = new HashMap<Node,Set<Node>>();
// map the join constraints to the type of join
- Map joinTypes = new HashMap();
+ Map<Node,URIReference> joinTypes = new HashMap<Node,URIReference>();
try {
// map each reference to the associated argument and type
@@ -843,24 +841,21 @@
logger.debug("mapping join constraint RDF nodes to join constraint objects");
// collect all arguments together into constraints and map the node to the constraint
- Iterator entries = constraintLinks.entrySet().iterator();
- while (entries.hasNext()) {
- // work with constraint/argument-set pair
- Map.Entry entry = (Map.Entry)entries.next();
+ for (Map.Entry<Node,Set<Node>> entry: constraintLinks.entrySet()) {
// get the constraint node in question
- Node constraintNode = (Node)entry.getKey();
+ Node constraintNode = entry.getKey();
// see if it maps to a constraint
if (constraintMap.get(constraintNode) == null) {
// the constraint does not exist
// get the argument nodes
- Set args = (Set)entry.getValue();
+ Set<Node> args = entry.getValue();
// get the constraint's type
- Node type = (Node)joinTypes.get(constraintNode);
+ Node type = joinTypes.get(constraintNode);
if (type == null) {
throw new KruleStructureException("No type available on join constraint");
}
// convert the RDF nodes to constraints
- List constraintArgs = getConstraints(args, constraintLinks, joinTypes);
+ List<ConstraintExpression> constraintArgs = getConstraints(args, constraintLinks, joinTypes);
ConstraintExpression joinConstraint = newJoinConstraint(type, constraintArgs);
logger.debug("mapped " + constraintNode + " -> " + joinConstraint);
// build the join constraint, and map the node to it
@@ -930,7 +925,7 @@
logger.debug("Retrieved all transitive constraints.");
// set up a mapping of constraints to predicate/SimpleConstraint pairs
- Map transMap = new HashMap();
+ Map<Node,Map<Node,Node>> transMap = new HashMap<Node,Map<Node,Node>>();
try {
// accumulate the transitive arguments
@@ -947,15 +942,13 @@
logger.debug("Mapped all transitive properties");
// build a new transconstraint for each transitive constraint node
- Iterator it = transMap.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry tEntry = (Map.Entry)it.next();
- Node constraintNode = (Node)tEntry.getKey();
- Map arguments = (Map)tEntry.getValue();
+ for (Map.Entry<Node,Map<Node,Node>> tEntry: transMap.entrySet()) {
+ Node constraintNode = tEntry.getKey();
+ Map<Node,Node> arguments = tEntry.getValue();
Constraint constraint;
// build the constraint based on the arguments
if (arguments.size() == 1) {
- Node sc = (Node)arguments.get(TRANSITIVE_ARGUMENT);
+ Node sc = arguments.get(TRANSITIVE_ARGUMENT);
if (sc == null) {
throw new KruleStructureException("Transitive argument not correct");
}
@@ -963,8 +956,8 @@
// get the simple constraint and build the transitive constraint around it
constraint = new SingleTransitiveConstraint((Constraint)constraintMap.get(sc));
} else if (arguments.size() == 2) {
- Node sc = (Node)arguments.get(TRANSITIVE_ARGUMENT);
- Node anchor = (Node)arguments.get(ANCHOR_ARGUMENT);
+ Node sc = arguments.get(TRANSITIVE_ARGUMENT);
+ Node anchor = arguments.get(ANCHOR_ARGUMENT);
if (sc == null || anchor == null) {
throw new KruleStructureException("Transitive arguments not correct");
}
@@ -994,24 +987,22 @@
* @param typeMap Maps constraint nodes to their type. Used to create a new constraint.
* @throws KruleStructureException There was an error in the RDF data structure.
*/
- private List getConstraints(Set constraints, Map constraintLinks, Map typeMap) throws KruleStructureException {
+ private List<ConstraintExpression> getConstraints(Set<Node> constraints, Map<Node,Set<Node>> constraintLinks, Map<Node,URIReference> typeMap) throws KruleStructureException {
logger.debug("converting nodes to constraint list: " + constraints);
// build the return list
- List cList = new ArrayList();
+ List<ConstraintExpression> cList = new ArrayList<ConstraintExpression>();
// go through the arguments
- Iterator cit = constraints.iterator();
- while (cit.hasNext()) {
- Node cNode = (Node)cit.next();
+ for (Node cNode: constraints) {
logger.debug("converting: " + cNode);
// get the constraint expression object
ConstraintExpression constraintExpr = (ConstraintExpression)constraintMap.get(cNode);
if (constraintExpr == null) {
logger.debug(cNode.toString() + " not yet mapped to constraint");
// constraint expression object does not yet exist, get its arguments
- Set constraintArgNodes = (Set)constraintLinks.get(cNode);
+ Set<Node> constraintArgNodes = constraintLinks.get(cNode);
// build the constraint expression - get the arguments as a list of constraints
- List constraintArgs = getConstraints(constraintArgNodes, constraintLinks, typeMap);
+ List<ConstraintExpression> constraintArgs = getConstraints(constraintArgNodes, constraintLinks, typeMap);
constraintExpr = newJoinConstraint((Node)typeMap.get(cNode), constraintArgs);
}
// add the constraint argument to the list
@@ -1028,7 +1019,7 @@
* @param args The list of arguments for the constraint.
* @return a new join constraint of the correct type.
*/
- private ConstraintExpression newJoinConstraint(Node type, List args) throws KruleStructureException {
+ private ConstraintExpression newJoinConstraint(Node type, List<ConstraintExpression> args) throws KruleStructureException {
logger.debug("Building join constraint of type <" + type + ">: " + args);
if (type.equals(CONSTRAINT_CONJUNCTION)) {
@@ -1041,31 +1032,6 @@
/**
- * Sets a property for a node, creating the entry if it does not exist yet.
- *
- * @param map The mapping of nodes to property/values.
- * @param node The node to set the property for.
- * @param predicate The property to set.
- * @param object The value to set the property to.
- */
- private static void addProperty(Map map, Node node, URIReference predicate, URIReference object) {
- // get the current set of properties
- Map pv = (Map)map.get(node);
- // check that the map exists
- if (pv == null) {
- // no, so create
- pv = new HashMap();
- pv.put(predicate, object);
- // add to the map
- map.put(node, pv);
- } else {
- // update the map to hold the new value
- pv.put(predicate, object);
- }
- }
-
-
- /**
* Converts an RDF Node to a constraint element.
*
* @param node The node to convert.
@@ -1104,13 +1070,13 @@
* @param predicate The property to set.
* @param object The value to set the property to.
*/
- private static void addProperty(Map map, Node node, URIReference predicate, Node object) {
+ private static void addProperty(Map<Node,Map<Node,Node>> map, Node node, URIReference predicate, Node object) {
// get the current set of properties
- Map pv = (Map)map.get(node);
+ Map<Node,Node> pv = map.get(node);
// check that the map exists
if (pv == null) {
// no, so create
- pv = new HashMap();
+ pv = new HashMap<Node,Node>();
pv.put(predicate, object);
// add to the map
map.put(node, pv);
@@ -1128,13 +1094,13 @@
* @param node1 The node to map.
* @param node2 The node to map it to.
*/
- private static void addLink(Map map, Node node1, Node node2) {
+ private static void addLink(Map<Node,Set<Node>> map, Node node1, Node node2) {
// get the current set of properties
- Set links = (Set)map.get(node1);
+ Set<Node> links = map.get(node1);
// check that the set exists
if (links == null) {
// no, so create
- links = new HashSet();
+ links = new HashSet<Node>();
links.add(node2);
// add to the map
map.put(node1, links);
Modified: branches/nw-interface/src/jar/krule/java/org/mulgara/krule/QueryStruct.java
===================================================================
--- branches/nw-interface/src/jar/krule/java/org/mulgara/krule/QueryStruct.java 2007-10-23 03:33:36 UTC (rev 494)
+++ branches/nw-interface/src/jar/krule/java/org/mulgara/krule/QueryStruct.java 2007-10-24 15:03:08 UTC (rev 495)
@@ -35,6 +35,8 @@
import java.util.Map;
import org.apache.log4j.Logger;
+import org.jrdf.graph.Literal;
+import org.jrdf.graph.Node;
import org.jrdf.graph.URIReference;
import org.mulgara.itql.VariableFactoryImpl;
import org.mulgara.query.ConstantValue;
@@ -44,6 +46,7 @@
import org.mulgara.query.ModelExpression;
import org.mulgara.query.ModelResource;
import org.mulgara.query.ModelUnion;
+import org.mulgara.query.Order;
import org.mulgara.query.Query;
import org.mulgara.query.UnconstrainedAnswer;
import org.mulgara.query.Variable;
@@ -72,8 +75,8 @@
/** The selection list. */
private ConstraintElement[] select = new ConstraintElement[3];
- /** List of elements which are variables. */
- private List variables;
+ /** List of elements which are variables, or ConstantValues. */
+ private List<Object> variables;
/** The model expresison for the query. */
private ModelExpression models;
@@ -96,7 +99,12 @@
* @throws IllegalArgumentException If the types are incorrect, the elements are not named as expected,
* or the references are not found in the references map.
*/
- public QueryStruct(URIReference[] vs, URIReference[] types, Map alias, Map uriReferences, Map varReferences, Map litReferences) {
+ public QueryStruct(
+ URIReference[] vs, URIReference[] types, Map<String,URI> alias,
+ Map<URIReference,URIReference> uriReferences, Map<URIReference,Variable> varReferences,
+ Map<Node,Literal> litReferences
+ ) {
+
if (vs.length != 3 && types.length != 3) {
throw new IllegalArgumentException("Wrong number of elements for a rule query");
}
@@ -104,7 +112,7 @@
VariableFactory variableFactory = new VariableFactoryImpl();
// set up a list of variables
- variables = new ArrayList();
+ variables = new ArrayList<Object>();
// convert the parameters to usable objects
for (int i = 0; i < 3; i++) {
@@ -208,9 +216,10 @@
*
* @return a new {@link org.mulgara.query.Query}
*/
+ @SuppressWarnings("unchecked")
public Query extractQuery() {
logger.debug("Extracting query");
- return new Query(variables, models, where, having, Collections.EMPTY_LIST, null, 0, new UnconstrainedAnswer());
+ return new Query(variables, models, where, having, (List<Order>)Collections.EMPTY_LIST, null, 0, new UnconstrainedAnswer());
}
}
Modified: branches/nw-interface/src/jar/krule/java/org/mulgara/krule/RuleStructure.java
===================================================================
--- branches/nw-interface/src/jar/krule/java/org/mulgara/krule/RuleStructure.java 2007-10-23 03:33:36 UTC (rev 494)
+++ branches/nw-interface/src/jar/krule/java/org/mulgara/krule/RuleStructure.java 2007-10-24 15:03:08 UTC (rev 495)
@@ -30,8 +30,6 @@
// Java 2 standard packages
import java.net.URI;
import java.io.Serializable;
-import java.rmi.RemoteException;
-import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -67,31 +65,31 @@
private static Logger logger = Logger.getLogger(RuleStructure.class.getName());
/** The rules in the framework. */
- private Set rules;
+ private Set<Rule> rules;
/** Map of rule names to the rule. */
- private Map ruleMap;
+ private Map<String,Rule> ruleMap;
- /** The model containing the base data. */
+ /** The model containing the base data. Current unused. */
private URI baseModel;
/** The terget model to contain the entailments. */
private URI targetModel;
/** The current list of rules that have to be run. */
- private LinkedHashSet runQueue;
+ private LinkedHashSet<Rule> runQueue;
/** The set of axioms pertinent to these rules. */
- private Set axioms;
+ private Set<org.jrdf.graph.Triple> axioms;
/**
* Principle constructor.
*/
public RuleStructure() {
- rules = new HashSet();
- ruleMap = new HashMap();
- runQueue = new LinkedHashSet();
+ rules = new HashSet<Rule>();
+ ruleMap = new HashMap<String,Rule>();
+ runQueue = new LinkedHashSet<Rule>();
axioms = null;
}
@@ -116,8 +114,8 @@
*/
public void setTrigger(String src, String dest) throws InitializerException {
// get the rules
- Rule srcRule = (Rule)ruleMap.get(src);
- Rule destRule = (Rule)ruleMap.get(dest);
+ Rule srcRule = ruleMap.get(src);
+ Rule destRule = ruleMap.get(dest);
// check that the rules exist
if (srcRule == null || destRule == null) {
throw new InitializerException("Nonexistent rule: " + srcRule == null ? src : dest);
@@ -134,7 +132,7 @@
* @param axioms A {@link java.util.Set} of {@link org.jrdf.graph.Triple}s
* comprising axiomatic statements.
*/
- public void setAxioms(Set axioms) {
+ public void setAxioms(Set<org.jrdf.graph.Triple> axioms) {
this.axioms = axioms;
}
@@ -164,7 +162,7 @@
*
* @return An iterator for the rules.
*/
- public Iterator getRuleIterator() {
+ public Iterator<Rule> getRuleIterator() {
return rules.iterator();
}
@@ -176,11 +174,7 @@
*/
public String toString() {
String result = "Rules = {\n";
- Iterator i = rules.iterator();
- while (i.hasNext()) {
- Rule r = (Rule)i.next();
- result += r.getName() + "\n";
- }
+ for (Rule r: rules) result += r.getName() + "\n";
result += "}";
return result;
}
@@ -192,26 +186,29 @@
* @param base The URI of the base data to apply rules to.
*/
public void setBaseModel(URI base) {
- Iterator it = rules.iterator();
- while (it.hasNext()) {
- Rule rule = (Rule)it.next();
- rule.setBaseModel(base);
- }
+ baseModel = base;
+ for (Rule rule: rules) rule.setBaseModel(base);
}
/**
+ * Get the base model for the rules. Currently unused.
+ *
+ * @param base The URI of the base data to apply rules to.
+ */
+ public URI setBaseModel() {
+ return baseModel;
+ }
+
+
+ /**
* Set the target model for the rules.
*
* @param target The URI of the target model to insert inferences into.
*/
public void setTargetModel(URI target) {
targetModel = target;
- Iterator it = rules.iterator();
- while (it.hasNext()) {
- Rule rule = (Rule)it.next();
- rule.setTargetModel(target);
- }
+ for (Rule rule: rules) rule.setTargetModel(target);
}
@@ -229,7 +226,7 @@
}
Session session = (Session)params;
// set up the run queue
- runQueue = new LinkedHashSet(rules);
+ runQueue = new LinkedHashSet<Rule>(rules);
// fill the run queue
runQueue.addAll(rules);
Rule currentRule = null;
@@ -294,10 +291,10 @@
*/
private Rule popRunQueue() {
// get an iterator for the queue
- Iterator iterator = runQueue.iterator();
+ Iterator<Rule> iterator = runQueue.iterator();
// this queue must have data in it
assert iterator.hasNext();
- Rule head = (Rule)iterator.next();
+ Rule head = iterator.next();
iterator.remove();
return head;
}
More information about the Mulgara-svn
mailing list