org.exist.xquery
Class XQueryContext

java.lang.Object
  extended byorg.exist.xquery.XQueryContext
Direct Known Subclasses:
ModuleContext

public class XQueryContext
extends java.lang.Object

The current XQuery execution context. Contains the static as well as the dynamic XQuery context components.

Author:
Wolfgang Meier (wolfgang@exist-db.org)

Field Summary
static java.lang.String HTTP_SESSIONVAR_XMLDB_USER
           
static java.lang.String XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR
           
static java.lang.String XQUERY_LOCAL_NS
           
 
Constructor Summary
XQueryContext(DBBroker broker, AccessContext accessCtx)
           
XQueryContext(XQueryContext copyFrom)
           
 
Method Summary
 void addForwardReference(FunctionCall call)
          Add a forward reference to an undeclared function.
 void addOption(java.lang.String qnameString, java.lang.String contents)
           
 boolean checkModulesValid()
          For compiled expressions: check if the source of any module imported by the current query has changed since compilation.
 void clearNamespaces()
          Clear all user-defined prefix/namespace mappings.
 void declareFunction(UserDefinedFunction function)
          Declare a user-defined function.
 Variable declareGlobalVariable(Variable var)
          Declare a global variable as by "declare variable".
 void declareInScopeNamespace(java.lang.String prefix, java.lang.String uri)
          Declare an in-scope namespace.
 void declareNamespace(java.lang.String prefix, java.lang.String uri)
          Declare a user-defined prefix/namespace mapping.
 void declareNamespaces(java.util.Map namespaceMap)
           
 Variable declareVariable(java.lang.String qname, java.lang.Object value)
          Declare a user-defined variable.
 LocalVariable declareVariableBinding(LocalVariable var)
          Declare a local variable.
 void finishBatchTransaction()
          Completes a batch transaction, by committing the transaction and calling finish on any triggers set by setBatchTransactionTrigger()
 void functionEnd()
          Report the end of the currently executed function.
 void functionStart(FunctionSignature signature)
          Report the start of a function execution.
 AccessContext getAccessContext()
           
 AnyURIValue getBaseURI()
          Get the base URI of the evaluation context.
 Txn getBatchTransaction()
          Get the Transaction for the batch
 DBBroker getBroker()
          Get the DBBroker instance used for the current query.
 java.text.Collator getCollator(java.lang.String uri)
           
 int getContextPosition()
          Get the current context position, i.e.
 int getCurrentStackSize()
          Returns the current size of the stack.
 java.lang.String getDefaultCollation()
           
 java.text.Collator getDefaultCollator()
           
 java.lang.String getDefaultFunctionNamespace()
          Returns the current default function namespace.
 MemTreeBuilder getDocumentBuilder()
          Get the document builder currently used for creating temporary document fragments.
 int getExpressionCount()
          Returns the number of expression objects in the internal representation of the query.
 DocumentSet getLockedDocuments()
          Returns the set of documents that have been loaded and locked during query execution.
 Module getModule(java.lang.String namespaceURI)
          Get the built-in module registered for the given namespace URI.
 java.lang.String getModuleLoadPath()
           
 java.util.Iterator getModules()
           
 Option getOption(QName qname)
           
 ExistPDP getPDP()
          Convenience method that returns the XACML Policy Decision Point for this database instance.
 Pragma getPragma(java.lang.String name, java.lang.String contents)
           
 java.lang.String getPrefixForURI(java.lang.String uri)
           
 Profiler getProfiler()
          Returns the Profiler instance of this context if profiling is enabled.
 Expression getRootExpression()
          Returns the root expression of the XQuery associated with this context.
 java.util.Iterator getSignaturesForFunction(QName name)
           
 DocumentSet getStaticallyKnownDocuments()
           
 java.lang.String getURIForPrefix(java.lang.String prefix)
          Return the namespace URI mapped to the registered prefix or null if the prefix is not registered.
 User getUser()
          Get the user which executes the current query.
 XQueryWatchDog getWatchDog()
           
 java.lang.Object getXQueryContextVar(java.lang.String name)
          Get an XQuery Context variable.
 boolean hasBatchTransaction()
          Determines if a batch transaction should be performed
 void importModule(java.lang.String namespaceURI, java.lang.String prefix, java.lang.String location)
          Import a module and make it available in this context.
 boolean isBackwardsCompatible()
          XPath 1.0 backwards compatibility turned on? In XPath 1.0 compatible mode, additional conversions will be applied to values if a numeric value is expected.
 boolean isProfilingEnabled()
           
 boolean isProfilingEnabled(int verbosity)
           
 boolean isVarDeclared(QName qname)
           
 Module loadBuiltInModule(java.lang.String namespaceURI, java.lang.String moduleClass)
          Load a built-in module from the given class name and assign it to the namespace URI.
 java.util.Iterator localFunctions()
           
 boolean lockDocumentsOnLoad()
          Should loaded documents be locked?
 LocalVariable markLocalVariables(boolean newContext)
          Returns the last variable on the local variable stack.
 void popDocumentContext()
           
 void popInScopeNamespaces()
           
 void popLocalVariables(LocalVariable var)
          Restore the local variable stack to the position marked by variable var.
 void popNamespaceContext()
           
 void prepare()
          Prepares the current context before xquery execution
 void proceed()
           
 void proceed(Expression expr)
           
 void proceed(Expression expr, MemTreeBuilder builder)
           
 void pushDocumentContext()
          Push any document fragment created within the current execution context on the stack.
 void pushInScopeNamespaces()
          Push all in-scope namespace declarations onto the stack.
 void pushNamespaceContext()
           
 void recover()
           
 void registerUpdateListener(UpdateListener listener)
           
 void releaseLockedDocuments()
          Release all locks on documents that have been locked during query execution.
 DocumentSet releaseUnusedDocuments(Sequence seq)
          Release all locks on documents not being referenced by the sequence.
 void removeNamespace(java.lang.String uri)
          Removes the namespace URI from the prefix/namespace mappings table.
 void reset()
          Prepare this XQueryContext to be reused.
 void resolveForwardReferences()
          Resolve all forward references to previously undeclared functions.
 UserDefinedFunction resolveFunction(QName name, int argCount)
          Resolve a user-defined function.
 Variable resolveVariable(QName qname)
          Try to resolve a variable.
 Variable resolveVariable(java.lang.String name)
          Try to resolve a variable.
 void setBackwardsCompatibility(boolean backwardsCompatible)
          Turn on/off XPath 1.0 backwards compatibility.
 void setBaseURI(AnyURIValue uri)
          Set the base URI for the evaluation context.
 void setBaseURI(AnyURIValue uri, boolean setInProlog)
          Set the base URI for the evaluation context.
 void setBatchTransactionTrigger(DocumentImpl doc)
          Set's that a trigger should be executed for the provided document as part of the batch transaction
 void setBroker(DBBroker broker)
           
 void setContextPosition(int pos)
          Set the current context position, i.e.
 void setDefaultCollation(java.lang.String uri)
          Set the default collation to be used by all operators and functions on strings.
 void setDefaultFunctionNamespace(java.lang.String uri)
          Set the default function namespace.
 void setLockDocumentsOnLoad(boolean lock)
          If lock is true, all documents loaded during query execution will be locked.
 void setModuleLoadPath(java.lang.String path)
          Set the path to a base directory where modules should be loaded from.
 void setRootExpression(Expression expr)
          Called from the XQuery compiler to set the root expression for this context.
 void setStaticallyKnownDocuments(DocumentSet set)
           
 void setStaticallyKnownDocuments(XmldbURI[] docs)
          Set the set of statically known documents for the current execution context.
 void setStripWhitespace(boolean strip)
           
 void setXQueryContextVar(java.lang.String name, java.lang.Object XQvar)
          Set an XQuery Context variable.
 void setXQuerySerializer(java.lang.String name, boolean indent, boolean omitxmldeclaration)
          Set the serializer to use for output Used by the context extension module; called by context:set-serializer().
 void startBatchTransaction()
          Starts a batch Transaction
 DocumentImpl storeTemporaryDoc(DocumentImpl doc)
          Store the supplied data to a temporary document fragment.
 boolean stripWhitespace()
          Returns true if whitespace between constructed element nodes should be stripped by default.
 boolean tailRecursiveCall(FunctionSignature signature)
          Check if the specified function signature is found in the current function called stack.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

XQUERY_LOCAL_NS

public static final java.lang.String XQUERY_LOCAL_NS
See Also:
Constant Field Values

XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR

public static final java.lang.String XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR
See Also:
Constant Field Values

HTTP_SESSIONVAR_XMLDB_USER

public static final java.lang.String HTTP_SESSIONVAR_XMLDB_USER
See Also:
Constant Field Values
Constructor Detail

XQueryContext

public XQueryContext(DBBroker broker,
                     AccessContext accessCtx)

XQueryContext

public XQueryContext(XQueryContext copyFrom)
Method Detail

prepare

public void prepare()
Prepares the current context before xquery execution


getAccessContext

public AccessContext getAccessContext()

isProfilingEnabled

public boolean isProfilingEnabled()
Returns:
true if profiling is enabled for this context.

isProfilingEnabled

public boolean isProfilingEnabled(int verbosity)

getProfiler

public Profiler getProfiler()
Returns the Profiler instance of this context if profiling is enabled.

Returns:
the profiler instance.

setRootExpression

public void setRootExpression(Expression expr)
Called from the XQuery compiler to set the root expression for this context.

Parameters:
expr -

getRootExpression

public Expression getRootExpression()
Returns the root expression of the XQuery associated with this context.

Returns:
root expression

getExpressionCount

public int getExpressionCount()
Returns the number of expression objects in the internal representation of the query. Used to estimate the size of the query.

Returns:
number of expression objects

declareNamespace

public void declareNamespace(java.lang.String prefix,
                             java.lang.String uri)
                      throws XPathException
Declare a user-defined prefix/namespace mapping. eXist internally keeps a table containing all prefix/namespace mappings it found in documents, which have been previously stored into the database. These default mappings need not to be declared explicitely.

Parameters:
prefix -
uri -
Throws:
XPathException

declareNamespaces

public void declareNamespaces(java.util.Map namespaceMap)

declareInScopeNamespace

public void declareInScopeNamespace(java.lang.String prefix,
                                    java.lang.String uri)
Declare an in-scope namespace. This is called during query execution.

Parameters:
prefix -
uri -

getDefaultFunctionNamespace

public java.lang.String getDefaultFunctionNamespace()
Returns the current default function namespace.

Returns:
current default function namespace

setDefaultFunctionNamespace

public void setDefaultFunctionNamespace(java.lang.String uri)
                                 throws XPathException
Set the default function namespace. By default, this points to the namespace for XPath built-in functions.

Parameters:
uri -
Throws:
XPathException

setDefaultCollation

public void setDefaultCollation(java.lang.String uri)
                         throws XPathException
Set the default collation to be used by all operators and functions on strings. Throws an exception if the collation is unknown or cannot be instantiated.

Parameters:
uri -
Throws:
XPathException

getDefaultCollation

public java.lang.String getDefaultCollation()

getCollator

public java.text.Collator getCollator(java.lang.String uri)
                               throws XPathException
Throws:
XPathException

getDefaultCollator

public java.text.Collator getDefaultCollator()

getURIForPrefix

public java.lang.String getURIForPrefix(java.lang.String prefix)
Return the namespace URI mapped to the registered prefix or null if the prefix is not registered.

Parameters:
prefix -
Returns:
namespace

getPrefixForURI

public java.lang.String getPrefixForURI(java.lang.String uri)
Parameters:
uri -
Returns:
the prefix mapped to the registered URI or null if the URI is not registered.

removeNamespace

public void removeNamespace(java.lang.String uri)
Removes the namespace URI from the prefix/namespace mappings table.

Parameters:
uri -

clearNamespaces

public void clearNamespaces()
Clear all user-defined prefix/namespace mappings.


setStaticallyKnownDocuments

public void setStaticallyKnownDocuments(XmldbURI[] docs)
Set the set of statically known documents for the current execution context. These documents will be processed if no explicit document set has been set for the current expression with fn:doc() or fn:collection().

Parameters:
docs -

setStaticallyKnownDocuments

public void setStaticallyKnownDocuments(DocumentSet set)

getStaticallyKnownDocuments

public DocumentSet getStaticallyKnownDocuments()
                                        throws XPathException
Returns:
set of statically known documents.
Throws:
XPathException

lockDocumentsOnLoad

public boolean lockDocumentsOnLoad()
Should loaded documents be locked?

See Also:
setLockDocumentsOnLoad(boolean)

setLockDocumentsOnLoad

public void setLockDocumentsOnLoad(boolean lock)
If lock is true, all documents loaded during query execution will be locked. This way, we avoid that query results become invalid before the entire result has been processed by the client code. All attempts to modify nodes which are part of the result set will be blocked. However, it is the client's responsibility to proper unlock all documents once processing is completed.

Parameters:
lock -

getLockedDocuments

public DocumentSet getLockedDocuments()
Returns the set of documents that have been loaded and locked during query execution.

Returns:
set of loaded and locked documents
See Also:
setLockDocumentsOnLoad(boolean)

releaseLockedDocuments

public void releaseLockedDocuments()
Release all locks on documents that have been locked during query execution.

See Also:
setLockDocumentsOnLoad(boolean)

releaseUnusedDocuments

public DocumentSet releaseUnusedDocuments(Sequence seq)
                                   throws XPathException
Release all locks on documents not being referenced by the sequence. This is called after query execution has completed. Only locks on those documents contained in the final result set will be preserved. All other locks are released as they are no longer needed.

Parameters:
seq -
Throws:
XPathException

reset

public void reset()
Prepare this XQueryContext to be reused. This should be called when adding an XQuery to the cache.


stripWhitespace

public boolean stripWhitespace()
Returns true if whitespace between constructed element nodes should be stripped by default.


setStripWhitespace

public void setStripWhitespace(boolean strip)

getModules

public java.util.Iterator getModules()
Returns:
iterator over all built-in modules currently registered.

getModule

public Module getModule(java.lang.String namespaceURI)
Get the built-in module registered for the given namespace URI.

Parameters:
namespaceURI -
Returns:
built-in module

checkModulesValid

public boolean checkModulesValid()
For compiled expressions: check if the source of any module imported by the current query has changed since compilation.


loadBuiltInModule

public Module loadBuiltInModule(java.lang.String namespaceURI,
                                java.lang.String moduleClass)
Load a built-in module from the given class name and assign it to the namespace URI. The specified class should be a subclass of Module. The method will try to instantiate the class. If the class is not found or an exception is thrown, the method will silently fail. The namespace URI has to be equal to the namespace URI declared by the module class. Otherwise, the module is not loaded.

Parameters:
namespaceURI -
moduleClass -

getPDP

public ExistPDP getPDP()
Convenience method that returns the XACML Policy Decision Point for this database instance. If XACML has not been enabled, this returns null.

Returns:
the PDP for this database instance, or null if XACML is disabled

declareFunction

public void declareFunction(UserDefinedFunction function)
                     throws XPathException
Declare a user-defined function. All user-defined functions are kept in a single hash map.

Parameters:
function -
Throws:
XPathException

resolveFunction

public UserDefinedFunction resolveFunction(QName name,
                                           int argCount)
                                    throws XPathException
Resolve a user-defined function.

Parameters:
name -
Returns:
user-defined function
Throws:
XPathException

getSignaturesForFunction

public java.util.Iterator getSignaturesForFunction(QName name)

localFunctions

public java.util.Iterator localFunctions()

declareVariableBinding

public LocalVariable declareVariableBinding(LocalVariable var)
                                     throws XPathException
Declare a local variable. This is called by variable binding expressions like "let" and "for".

Parameters:
var -
Throws:
XPathException

declareGlobalVariable

public Variable declareGlobalVariable(Variable var)
                               throws XPathException
Declare a global variable as by "declare variable".

Parameters:
var -
Throws:
XPathException

declareVariable

public Variable declareVariable(java.lang.String qname,
                                java.lang.Object value)
                         throws XPathException
Declare a user-defined variable. The value argument is converted into an XPath value (@see XPathUtil#javaObjectToXPath(Object)).

Parameters:
qname - the qualified name of the new variable. Any namespaces should have been declared before.
value - a Java object, representing the fixed value of the variable
Returns:
the created Variable object
Throws:
XPathException - if the value cannot be converted into a known XPath value or the variable QName references an unknown namespace-prefix.

resolveVariable

public Variable resolveVariable(java.lang.String name)
                         throws XPathException
Try to resolve a variable.

Parameters:
name - the qualified name of the variable as string
Returns:
the declared Variable object
Throws:
XPathException - if the variable is unknown

resolveVariable

public Variable resolveVariable(QName qname)
                         throws XPathException
Try to resolve a variable.

Parameters:
qname - the qualified name of the variable
Returns:
the declared Variable object
Throws:
XPathException - if the variable is unknown

isVarDeclared

public boolean isVarDeclared(QName qname)

setBackwardsCompatibility

public void setBackwardsCompatibility(boolean backwardsCompatible)
Turn on/off XPath 1.0 backwards compatibility. If turned on, comparison expressions will behave like in XPath 1.0, i.e. if any one of the operands is a number, the other operand will be cast to a double.

Parameters:
backwardsCompatible -

isBackwardsCompatible

public boolean isBackwardsCompatible()
XPath 1.0 backwards compatibility turned on? In XPath 1.0 compatible mode, additional conversions will be applied to values if a numeric value is expected.


getBroker

public DBBroker getBroker()
Get the DBBroker instance used for the current query. The DBBroker is the main database access object, providing access to all internal database functions.

Returns:
DBBroker instance

setBroker

public void setBroker(DBBroker broker)

getUser

public User getUser()
Get the user which executes the current query.

Returns:
user

getDocumentBuilder

public MemTreeBuilder getDocumentBuilder()
Get the document builder currently used for creating temporary document fragments. A new document builder will be created on demand.

Returns:
document builder

proceed

public void proceed()
             throws TerminatedException
Throws:
TerminatedException

proceed

public void proceed(Expression expr)
             throws TerminatedException
Throws:
TerminatedException

proceed

public void proceed(Expression expr,
                    MemTreeBuilder builder)
             throws TerminatedException
Throws:
TerminatedException

recover

public void recover()

getWatchDog

public XQueryWatchDog getWatchDog()

pushDocumentContext

public void pushDocumentContext()
Push any document fragment created within the current execution context on the stack.


popDocumentContext

public void popDocumentContext()

setBaseURI

public void setBaseURI(AnyURIValue uri)
Set the base URI for the evaluation context. This is the URI returned by the fn:base-uri() function.

Parameters:
uri -

setBaseURI

public void setBaseURI(AnyURIValue uri,
                       boolean setInProlog)
Set the base URI for the evaluation context. A base URI specified via the base-uri directive in the XQuery prolog overwrites any other setting.

Parameters:
uri -
setInProlog -

setModuleLoadPath

public void setModuleLoadPath(java.lang.String path)
Set the path to a base directory where modules should be loaded from. Relative module paths will be resolved against this directory. The property is usually set by the XQueryServlet or XQueryGenerator, but can also be specified manually.

Parameters:
path -

getModuleLoadPath

public java.lang.String getModuleLoadPath()

getBaseURI

public AnyURIValue getBaseURI()
Get the base URI of the evaluation context. This is the URI returned by the fn:base-uri() function.

Returns:
base URI of the evaluation context

setContextPosition

public void setContextPosition(int pos)
Set the current context position, i.e. the position of the currently processed item in the context sequence. This value is required by some expressions, e.g. fn:position().

Parameters:
pos -

getContextPosition

public int getContextPosition()
Get the current context position, i.e. the position of the currently processed item in the context sequence.

Returns:
current context position

pushInScopeNamespaces

public void pushInScopeNamespaces()
Push all in-scope namespace declarations onto the stack.


popInScopeNamespaces

public void popInScopeNamespaces()

pushNamespaceContext

public void pushNamespaceContext()

popNamespaceContext

public void popNamespaceContext()

markLocalVariables

public LocalVariable markLocalVariables(boolean newContext)
Returns the last variable on the local variable stack. The current variable context can be restored by passing the return value to popLocalVariables(LocalVariable).

Returns:
last variable on the local variable stack

popLocalVariables

public void popLocalVariables(LocalVariable var)
Restore the local variable stack to the position marked by variable var.

Parameters:
var -

getCurrentStackSize

public int getCurrentStackSize()
Returns the current size of the stack. This is used to determine where a variable has been declared.

Returns:
current size of the stack

functionStart

public void functionStart(FunctionSignature signature)
Report the start of a function execution. Adds the reported function signature to the function call stack.


functionEnd

public void functionEnd()
Report the end of the currently executed function. Pops the last function signature from the function call stack.


tailRecursiveCall

public boolean tailRecursiveCall(FunctionSignature signature)
Check if the specified function signature is found in the current function called stack. If yes, the function might be tail recursive and needs to be optimized.

Parameters:
signature -

importModule

public void importModule(java.lang.String namespaceURI,
                         java.lang.String prefix,
                         java.lang.String location)
                  throws XPathException
Import a module and make it available in this context. The prefix and location parameters are optional. If prefix is null, the default prefix specified by the module is used. If location is null, the module will be read from the namespace URI.

Parameters:
namespaceURI -
prefix -
location -
Throws:
XPathException

addForwardReference

public void addForwardReference(FunctionCall call)
Add a forward reference to an undeclared function. Forward references will be resolved later.

Parameters:
call -

resolveForwardReferences

public void resolveForwardReferences()
                              throws XPathException
Resolve all forward references to previously undeclared functions.

Throws:
XPathException

addOption

public void addOption(java.lang.String qnameString,
                      java.lang.String contents)
               throws XPathException
Throws:
XPathException

getOption

public Option getOption(QName qname)

getPragma

public Pragma getPragma(java.lang.String name,
                        java.lang.String contents)
                 throws XPathException
Throws:
XPathException

storeTemporaryDoc

public DocumentImpl storeTemporaryDoc(DocumentImpl doc)
                               throws XPathException
Store the supplied data to a temporary document fragment.

Parameters:
doc -
Throws:
XPathException

setXQueryContextVar

public void setXQueryContextVar(java.lang.String name,
                                java.lang.Object XQvar)
Set an XQuery Context variable. Used by the context extension module; called by context:set-var().

Parameters:
name - The variable name
XQvar - The variable value, may be of any xs: type

getXQueryContextVar

public java.lang.Object getXQueryContextVar(java.lang.String name)
Get an XQuery Context variable. Used by the context extension module; called by context:get-var().

Parameters:
name - The variable name
Returns:
The variable value indicated by name.

startBatchTransaction

public void startBatchTransaction()
                           throws TransactionException
Starts a batch Transaction

Throws:
TransactionException

hasBatchTransaction

public boolean hasBatchTransaction()
Determines if a batch transaction should be performed

Returns:
true if a batch update transaction should be performed

getBatchTransaction

public Txn getBatchTransaction()
Get the Transaction for the batch

Returns:
The Transaction

setBatchTransactionTrigger

public void setBatchTransactionTrigger(DocumentImpl doc)
Set's that a trigger should be executed for the provided document as part of the batch transaction

Parameters:
doc - The document to trigger for

finishBatchTransaction

public void finishBatchTransaction()
                            throws TransactionException
Completes a batch transaction, by committing the transaction and calling finish on any triggers set by setBatchTransactionTrigger()

Throws:
TransactionException

setXQuerySerializer

public void setXQuerySerializer(java.lang.String name,
                                boolean indent,
                                boolean omitxmldeclaration)
                         throws XPathException
Set the serializer to use for output Used by the context extension module; called by context:set-serializer().

Parameters:
name - The name of the serializer to use
indent - Should the output be indented?
omitxmldeclaration - Should the output omit the xml declaration?
Throws:
XPathException

registerUpdateListener

public void registerUpdateListener(UpdateListener listener)


Copyright (C) Wolfgang Meier. All rights reserved.