//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018 Saxonica Limited. // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// package net.sf.saxon.query; import net.sf.saxon.Configuration; import net.sf.saxon.expr.Literal; import net.sf.saxon.expr.instruct.Executable; import net.sf.saxon.expr.instruct.GlobalParam; import net.sf.saxon.expr.instruct.GlobalVariable; import net.sf.saxon.expr.parser.CodeInjector; import net.sf.saxon.expr.parser.Location; import net.sf.saxon.expr.parser.OptimizerOptions; import net.sf.saxon.expr.sort.SimpleCollation; import net.sf.saxon.functions.FunctionLibrary; import net.sf.saxon.lib.*; import net.sf.saxon.om.*; import net.sf.saxon.trace.TraceCodeInjector; import net.sf.saxon.trans.XPathException; import net.sf.saxon.type.AnyItemType; import net.sf.saxon.type.ItemType; import net.sf.saxon.value.SequenceType; import javax.xml.transform.ErrorListener; import javax.xml.transform.Source; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.*; /** * StaticQueryContext contains information used to build a StaticContext for use when processing XQuery * expressions. *
Despite its name, StaticQueryContext no longer implements the StaticContext
* interface, which means it cannot be used directly by Saxon when parsing a query. Instead it is first copied
* to create a QueryModule object, which does implement the StaticContext interface.
The application constructs a StaticQueryContext * and initializes it with information about the context, for example, default namespaces, base URI, and so on. * When a query is compiled using this StaticQueryContext, the query parser makes a copy of the StaticQueryContext * and uses this internally, modifying it with information obtained from the query prolog, as well as information * such as namespace and variable declarations that can occur at any point in the query. The query parser does * not modify the original StaticQueryContext supplied by the calling application, which may therefore be used * for compiling multiple queries, serially or even in multiple threads.
*This class forms part of Saxon's published XQuery API. Methods that * are considered stable are labelled with the JavaDoc "since" tag. * The value 8.4 indicates a method introduced at or before Saxon 8.4; other * values indicate the version at which the method was introduced.
*In the longer term, this entire API may at some stage be superseded by a proposed * standard Java API for XQuery.
* * @since 8.4 */ public class StaticQueryContext { private Configuration config; private NamePool namePool; private String baseURI; private HashMapThis method is retained for backwards compatibility; however, it is merely a wrapper * around the method {@link Configuration#buildDocumentTree}, which should be called in preference.
* * @param source Any javax.xml.transform.Source object representing the document against * which queries will be executed. Note that a Saxon {@link net.sf.saxon.om.NodeInfo} * can be used as a Source. To use a third-party DOM Document as a source, create an instance of * {@link javax.xml.transform.dom.DOMSource} to wrap it. *For additional control over the way in which the source document is processed, * supply an {@link net.sf.saxon.lib.AugmentedSource} object and set appropriate * options on the object.
* @return the DocumentInfo representing the root node of the resulting document object. * @throws XPathException if building the document fails * @since 8.4 * @deprecated since 9.2: use {@link Configuration#buildDocumentTree(javax.xml.transform.Source)} */ /*@NotNull*/ public TreeInfo buildDocument(Source source) throws XPathException { return config.buildDocumentTree(source); } /** * Set the language version. * * @param version The XQuery language version. Must be 10 (="1.0") or 30 (="3.0") or 31 (="3.1"). * @since 9.2; changed in 9.3 to expect a DecimalValue rather than a string. Changed in 9.7 to * accept an int (30 = "3.0") and to allow "3.1". From 9.8.0.3 the supplied value is ignored * and the language version is always set to "3.1". */ public void setLanguageVersion(int version) { if (version==10 || version==30 || version==31) { // value is ignored } else { throw new IllegalArgumentException("languageVersion = " + version); } } /** * Get the language version * * @return the language version. Either "1.0" or "1.1". Default is "1.0". * @since 9.2; changed in 9.3 to return a DecimalValue rather than a string; * changed in 9.7 to return an int (30 = "3.0" and so on). Changed in 9.8.0.3 to * always return 31. */ public int getLanguageVersion() { return 31; } /** * Get any extension function library that was previously set. * * @return the extension function library, or null if none has been set. The result will always be null if called * in Saxon-HE; setting an extension function library requires the Saxon-PE or Saxon-EE versions of this class. * @since 9.4 */ /*@Nullable*/ public FunctionLibrary getExtensionFunctionLibrary() { return null; } /** * Ask whether compile-time generation of trace code was requested * * @return true if compile-time generation of code was requested * @since 9.0 */ public boolean isCompileWithTracing() { return codeInjector instanceof TraceCodeInjector; } /** * Request compile-time generation of trace code (or not) * * @param trace true if compile-time generation of trace code is required * @since 9.0 */ public void setCompileWithTracing(boolean trace) { if (trace) { codeInjector = new TraceCodeInjector(); } else { codeInjector = null; } } /** * Request that the parser should insert custom code into the expression tree * by calling a supplied CodeInjector to process each expression as it is parsed, * for example for tracing or performance measurement * * @param injector the CodeInjector to be used. May be null, in which case * no code is injected * @since 9.4 */ public void setCodeInjector( /*@Nullable*/ CodeInjector injector) { this.codeInjector = injector; } /** * Get any CodeInjector that has been registered * * @return the registered CodeInjector, or null * @since 9.4 */ /*@Nullable*/ public CodeInjector getCodeInjector() { return codeInjector; } /** * Ask whether XQuery Update is allowed * * @return true if XQuery update is supported by queries using this context */ public boolean isUpdating() { return isUpdating; } /** * Set the namespace inheritance mode * * @param inherit true if namespaces are inherited, false if not * @since 8.4 */ public void setInheritNamespaces(boolean inherit) { inheritNamespaces = inherit; } /** * Get the namespace inheritance mode * * @return true if namespaces are inherited, false if not * @since 8.4 */ public boolean isInheritNamespaces() { return inheritNamespaces; } /** * Set the namespace copy mode * * @param inherit true if namespaces are preserved, false if not * @since 8.4 */ public void setPreserveNamespaces(boolean inherit) { preserveNamespaces = inherit; } /** * Get the namespace copy mode * * @return true if namespaces are preserved, false if not * @since 8.4 */ public boolean isPreserveNamespaces() { return preserveNamespaces; } /** * Set the construction mode for this module * * @param mode one of {@link net.sf.saxon.lib.Validation#STRIP}, {@link net.sf.saxon.lib.Validation#PRESERVE} * @since 8.4 */ public void setConstructionMode(int mode) { constructionMode = mode; } /** * Get the current construction mode * * @return one of {@link net.sf.saxon.lib.Validation#STRIP}, {@link net.sf.saxon.lib.Validation#PRESERVE} * @since 8.4 */ public int getConstructionMode() { return constructionMode; } /** * Set the module location. Normally the module location is assumed to be line 1, column 1 of the * resource identified by the base URI. But a different location can be set, for example if the query * is embedded in an XML document, and this information will be available in diagnostics. * @param location the module location * @since 9.7 */ public void setModuleLocation(Location location) { this.moduleLocation = location; } /** * Get the module location. Normally the module location is assumed to be line 1, column 1 of the * resource identified by the base URI. But a different location can be set, for example if the query * is embedded in an XML document, and this information will be available in diagnostics. * @return the module location * @since 9.7 */ public Location getModuleLocation() { return moduleLocation; } /** * Set the optimizer options to be used for compiling queries that use this static context. * By default the optimizer options set in the {@link Configuration} are used. * * @param options the optimizer options to be used */ public void setOptimizerOptions(OptimizerOptions options) { this.optimizerOptions = options; } /** * Get the optimizer options being used for compiling queries that use this static context. * By default the optimizer options set in the {@link Configuration} are used. * * @return the optimizer options being used */ public OptimizerOptions getOptimizerOptions() { return this.optimizerOptions; } /** * Prepare an XQuery query for subsequent evaluation. The source text of the query * is supplied as a String. The base URI of the query is taken from the static context, * and defaults to the current working directory. *Note that this interface makes the caller responsible for decoding the query and * presenting it as a string of characters. This means it is likely that any encoding * specified in the query prolog will be ignored.
* * @param query The XQuery query to be evaluated, supplied as a string. * @return an XQueryExpression object representing the prepared expression * @throws net.sf.saxon.trans.XPathException * if the syntax of the expression is wrong, * or if it references namespaces, variables, or functions that have not been declared, * or contains other static errors. * @since 8.4 */ /*@NotNull*/ public XQueryExpression compileQuery(/*@NotNull*/ String query) throws XPathException { XQueryParser qp = (XQueryParser) config.newExpressionParser("XQ", isUpdating, 31); if (codeInjector != null) { qp.setCodeInjector(codeInjector); } else if (config.isCompileWithTracing()) { qp.setCodeInjector(new TraceCodeInjector()); } qp.setStreaming(isStreaming()); QueryModule mainModule = new QueryModule(this); return qp.makeXQueryExpression(query, mainModule, config); } /** * Prepare an XQuery query for subsequent evaluation. The Query is supplied * in the form of a Reader. The base URI of the query is taken from the static context, * and defaults to the current working directory. *Note that this interface makes the Reader responsible for decoding the query and * presenting it as a stream of characters. This means it is likely that any encoding * specified in the query prolog will be ignored. Also, some implementations of Reader * cannot handle a byte order mark.
* * @param source A Reader giving access to the text of the XQuery query to be compiled. * @return an XPathExpression object representing the prepared expression. * @throws net.sf.saxon.trans.XPathException * if the syntax of the expression is wrong, or if it references namespaces, * variables, or functions that have not been declared, or any other static error is reported. * @throws java.io.IOException if a failure occurs reading the supplied input. * @since 8.4 */ /*@Nullable*/ public synchronized XQueryExpression compileQuery(/*@NotNull*/ Reader source) throws XPathException, IOException { char[] buffer = new char[4096]; StringBuilder sb = new StringBuilder(4096); while (true) { int n = source.read(buffer); if (n > 0) { sb.append(buffer, 0, n); } else { break; } } return compileQuery(sb.toString()); } /** * Prepare an XQuery query for subsequent evaluation. The Query is supplied * in the form of a InputStream, with an optional encoding. If the encoding is not specified, * the query parser attempts to obtain the encoding by inspecting the input stream: it looks specifically * for a byte order mark, and for the encoding option in the version declaration of an XQuery prolog. * The encoding defaults to UTF-8. * The base URI of the query is taken from the static context, * and defaults to the current working directory. * * @param source An InputStream giving access to the text of the XQuery query to be compiled, as a stream * of octets * @param encoding The encoding used to translate characters to octets in the query source. The parameter * may be null: in this case the query parser attempts to infer the encoding by inspecting the source, * and if that fails, it assumes UTF-8 encoding * @return an XPathExpression object representing the prepared expression. * @throws net.sf.saxon.trans.XPathException * if the syntax of the expression is wrong, or if it references namespaces, * variables, or functions that have not been declared, or any other static error is reported. * @since 8.5 */ /*@Nullable*/ public synchronized XQueryExpression compileQuery(/*@NotNull*/ InputStream source, /*@Nullable*/ String encoding) throws XPathException { String query = QueryReader.readInputStream(source, encoding, config.getValidCharacterChecker()); return compileQuery(query); } /** * Compile an XQuery library module for subsequent evaluation. This method is supported * only in Saxon-EE * * @param query the content of the module, as a string * @throws XPathException if a static error exists in the query * @throws UnsupportedOperationException if not using Saxon-EE * @since 9.2 (changed in 9.3 to return void) */ public void compileLibrary(String query) throws XPathException { throw new XPathException("Separate compilation of query libraries requires Saxon-EE"); } /** * Prepare an XQuery library module for subsequent evaluation. This method is supported * only in Saxon-EE. The effect of the method is that subsequent query compilations using this static * context can import the module URI without specifying a location hint; the import then takes effect * without requiring the module to be compiled each time it is imported. * * @param source the content of the module, as a Reader which supplies the source code * @throws XPathException if a static error exists in the query * @throws IOException if the input cannot be read * @throws UnsupportedOperationException if not using Saxon-EE * @since 9.2 (changed in 9.3 to return void) */ public void compileLibrary(Reader source) throws XPathException, IOException { throw new XPathException("Separate compilation of query libraries requires Saxon-EE"); } /** * Prepare an XQuery library module for subsequent evaluation. This method is supported * only in Saxon-EE. The effect of the method is that subsequent query compilations using this static * context can import the module URI without specifying a location hint; the import then takes effect * without requiring the module to be compiled each time it is imported. * * @param source the content of the module, as an InputStream which supplies the source code * @param encoding the character encoding of the input stream. May be null, in which case the encoding * is inferred, for example by looking at the query declaration * @throws XPathException if a static error exists in the query * @throws IOException if the input cannot be read * @throws UnsupportedOperationException if not using Saxon-EE * @since 9.2 (changed in 9.3 to return void) */ public void compileLibrary(InputStream source, /*@Nullable*/ String encoding) throws XPathException, IOException { throw new UnsupportedOperationException("Separate compilation of query libraries requires Saxon-EE"); } /** * Get a previously compiled library module * * @param namespace the module namespace * @return the QueryLibrary if a module with this namespace has been compiled as a library module; * otherwise null. Always null when not using Saxon-EE. * @since 9.3 */ /*@Nullable*/ public QueryLibrary getCompiledLibrary(String namespace) { return null; } public CollectionChanged in Saxon 9.0 so that the namespaces resolved by the external namespace resolver * are available at run-time, just like namespaces declared in the query prolog. In consequence, * the supplied NamespaceResolver must now implement the * {@link net.sf.saxon.om.NamespaceResolver#iteratePrefixes()} method.
* * @param resolver the external namespace resolver */ public void setExternalNamespaceResolver(NamespaceResolver resolver) { externalNamespaceResolver = resolver; } /** * Get the external namespace resolver that has been registered using * setExternalNamespaceResolver(), if any. * * @return the external namespace resolver */ /*@Nullable*/ public NamespaceResolver getExternalNamespaceResolver() { return externalNamespaceResolver; } /** * Get the default function namespace * * @return the default function namespace (defaults to the fn: namespace) * @since 8.4 */ public String getDefaultFunctionNamespace() { return defaultFunctionNamespace; } /** * Set the default function namespace * * @param defaultFunctionNamespace The namespace to be used for unprefixed function calls * @since 8.4 */ public void setDefaultFunctionNamespace(String defaultFunctionNamespace) { this.defaultFunctionNamespace = defaultFunctionNamespace; } /** * Set the default element namespace * * @param uri the namespace URI to be used as the default namespace for elements and types * @since 8.4 */ public void setDefaultElementNamespace(String uri) { defaultElementNamespace = uri; declareNamespace("", uri); } /** * Get the default namespace for elements and types * * @return the namespace URI to be used as the default namespace for elements and types * @since 8.9 Modified in 8.9 to return the namespace URI as a string rather than an integer code */ /*@Nullable*/ public String getDefaultElementNamespace() { return defaultElementNamespace; } /** * Declare a global variable. This has the same effect as including a global variable declaration * in the Query Prolog of the main query module. A static error occurs when compiling the query if the * query prolog contains a declaration of the same variable. * * @param qName the qualified name of the variable * @param type the declared type of the variable * @param value the initial value of the variable. May be null if the variable is external. * @param external true if the variable is external, that is, if its value may be set at run-time. * @throws NullPointerException if the value is null, unless the variable is external * @throws XPathException if the value of the variable is not consistent with its type. * @since 9.1 */ public void declareGlobalVariable( StructuredQName qName, SequenceType type, Sequence> value, boolean external) throws XPathException { if (value == null && !external) { throw new NullPointerException("No initial value for declared variable"); } if (value != null && !type.matches(value, getConfiguration().getTypeHierarchy())) { throw new XPathException("Value of declared variable does not match its type"); } GlobalVariable var = external ? new GlobalParam() : new GlobalVariable(); var.setVariableQName(qName); var.setRequiredType(type); if (value != null) { var.setSelectExpression(Literal.makeLiteral(value.materialize())); } if (userDeclaredVariables == null) { userDeclaredVariables = new HashSet<>(); } userDeclaredVariables.add(var); } /** * Iterate over all the declared global variables * * @return an iterator over all the global variables that have been declared. They are returned * as instances of class {@link GlobalVariable} * @since 9.1 */ public IteratorIf the supplied listener is a StandardErrorListener, then a new copy will be made * using {@link StandardErrorListener#makeAnother(int)}
*If the supplied listener is not an {@link UnfailingErrorListener}, then it will be wrapped * in a {@link DelegatingErrorListener}.
* * @param listener the ErrorListener to be used */ public void setErrorListener(ErrorListener listener) { if (listener instanceof StandardErrorListener) { errorListener = ((StandardErrorListener) listener).makeAnother(Configuration.XQUERY); ((StandardErrorListener) errorListener).setRecoveryPolicy(Configuration.DO_NOT_RECOVER); } else if (listener instanceof UnfailingErrorListener) { errorListener = (UnfailingErrorListener) listener; } else { errorListener = new DelegatingErrorListener(listener); } } /** * Get the ErrorListener in use for this static context * * @return the registered ErrorListener */ public UnfailingErrorListener getErrorListener() { if (errorListener == null) { errorListener = config.getErrorListener(); } return errorListener; } /** * Say whether the query is allowed to be updating. XQuery update syntax will be rejected * during query compilation unless this flag is set. * * @param updating true if the query is allowed to use the XQuery Update facility * (requires Saxon-EE). If set to false, the query must not be an updating query. If set * to true, it may be either an updating or a non-updating query. * @since 9.1 */ public void setUpdatingEnabled(boolean updating) { isUpdating = updating; } /** * Ask whether the query is allowed to be updating * * @return true if the query is allowed to use the XQuery Update facility. Note that this * does not necessarily mean that the query is an updating query; but if the value is false, * the it must definitely be non-updating. * @since 9.1 */ public boolean isUpdatingEnabled() { return isUpdating; } }