Changes

Jump to navigation Jump to search
8,281 bytes added ,  11:25, 18 August 2021
Please bear in mind that the execution of Java code may cause side effects that conflict with the functional nature of XQuery, or may introduce new security risks to your project.
 
{{Mark|Updated with Version 9.6:}}
* With the middle dot notation, three adjacent dots can be used to specify array types.
* The path to the standard package {{Code|java.lang.}} can now be omitted.
* Java objects are now wrapped into function items.
* Results of constructor calls are always returned as function item.
* A new option {{Option|WRAPJAVA}} was added to control how Java values are converted to XQuery.
* The Mapping rules were refined and unified. The most important changes:
** {{Code|array(*)}} type added.
** {{Code|xs:integer}} values are converted to {{Code|long}} values.
** {{Code|xs:unsignedShort}} values are converted to {{Code|char}} values.
* All error messages were revised and improved.
=Identification=
# The last path segment of the URI is capitalized and rewritten to [https://en.wikipedia.org/wiki/CamelCase CamelCase].
The normalization steps are skipped if the URI is prefixed with {{Code|java:}}. The path to the standard package {{Code|java.lang.}} can be omitted:
* <code><nowiki>http://basex.org/modules/meta-data</nowiki></code> → <code>org.basex.modules.MetaData</code>
* <code>java:java.lang.String</code> → <code>java.lang.String</code>
* <code>StringBuilder</code> → <code>java.lang.StringBuilder</code>
==Functions and Variables==
Java constructors, functions and variables can be referenced and evaluated by the existing XQuery function syntax:
* The namespace of the function name identifies the Java class.
* The local part of the name, which is rewritten to camel case, identifies a variable or function of that class.
* The middle dot character <code>[httphttps://www.fileformat.info/info/unicode/char/b7/index.htm ·]</code> (<code>&amp;#xB7;</code>, a valid character in XQuery names, but not in Java) can be used to append exact Java parameter types to the function name. Class types must be referenced by their full path. Three adjacent dots can be used to address an array argument.
{| class="wikitable"
|- valign="top"
! TypeAddressed code
! XQuery
! Java
|- valign="top"
| Variable
| <code>Q{java.lang.Integer}MIN_VALUE()</code>| <code>[https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#MAX_VALUE Integer.MIN_VALUE]</code>
|- valign="top"
| Function
| <code>Q{java.lang.Object}hash-code($object)</code>| <code>[https://docsobject.oracle.comhashCode()</javase/8/docs/api/java/lang/Object.html#hashCodecode>|- valign="top"| Function with argument| <code>Q{String}split·String·int($string, ';', xs:int(3)) object</code>| <code>string.hashCodesplit(";", 3)]</code>
|- valign="top"
| Function Constructor with typesarray argument| <code>Q{java.lang.String}split·javanew·byte..lang.String·int($string, ';', xs:inthexBinary(3'414243'))</code>| <code>[https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.new String-int- string.split(";"new byte[] { 41, 42, 343 })]</code>
|}
As XQuery and Java have different type systems, XQuery arguments are must be converted to equivalent Java values, and the result of a Java function is converted back to an XQuery value (see [[#Data Types|Data Types]]).
If a the Java function you want to address is not founddetected, XQuery values you may need to be cast your values to the target type. For example, if a Java function expects a primitive {{Code|int}} value, you will need to convert your XQuery integers to {{Code|xs:int}}.
=Namespace Declarations=
In the following example, Java’s the Java {{Code|Math}} class is referenced. When executed, the query returns the cosine of an angle by calling the static method {{Code|cos()}}, and the value of π by addressing the static variable via {{Code|PI()}}:
<syntaxhighlight lang="xquery">
</syntaxhighlight>
With the [[XQuery 3.0#Expanded QNames|Expanded QName]] notation of XQuery 3.0,the namespace can directly be embedded in the function call:
<syntaxhighlight lang="xquery">
<syntaxhighlight lang="xquery">
declare namespace fw = "'java:java.io.FileWriter"';
let $file := fw:new('output.txt')
return (
<syntaxhighlight lang="xquery">
declare namespace br = 'java:java.io.BufferedReader';declare namespace fr = 'java:java.io.FileReader';
declare option db:checkstrings 'false';
(: write file :)
file:write-binary('00.bin', xs:hexBinary('00')),
(: read file :)let $br := br:new(fr:new('00.bin')) ! return ( br:readLine(.$br), br:close(.$br))
</syntaxhighlight>
Note that Java code cannot The option can also be pre-compiledspecified via a pragma: <syntaxhighlight lang="xquery">(# db:checkstrings #) { br:new(fr:new('00.bin')) ! (br:readLine(.), and will as such be evaluated slower than optimized XQuery codebr:close(.))}</syntaxhighlight>
=Module Imports=
An alternative solution is to access A Java code classes can also be instantiated by ''importing'' classes them as modules. a module: A new instance of the addressed class will be createdconstructed, which can then be referenced in the query body.
In the (side-effecting) example below, a HashSet instance is created, values are added, and the size of a Java hash the set is returned. The boolean values that are returned by As {{Code|set:add()}} are swallowedreturns boolean values, {{Function|Profiling|prof:void}} is used to swallow the values:
<syntaxhighlight lang="xquery">
</syntaxhighlight>
The execution of imported classes is more efficient than the execution of instances that are have been created at runtime via {{Code|new()}}. A drawback is that In turn, no arguments can be passed on to supplied in the class constructor. As a consequenceimport statement, and the import fails construction will only be successful if the addressed class has no default constructor, but at least one constructor with can be instantiated without arguments.
=Integration=
Java classes can be coupled even more closely to the BaseX core library.If a class inherits the abstract [https://github.com/BaseXdb/basex/blob/master/basex-core/src/main/java/org/basex/query/QueryModule.java QueryModule] class, the two variables [https://github.com/BaseXdb/basex/blob/master/basex-core/src/main/java/org/basex/query/QueryContext.java queryContext] and [https://github.com/BaseXdb/basex/blob/master/basex-core/src/main/java/org/basex/query/StaticContext.java staticContext] get available, which provide access to the global and static context of a query.
The [https://github.com/BaseXdb/basex/blob/master/basex-core/src/main/java/org/basex/query/QueryResource.java QueryResource] interface can be implemented to enforce finalizing operations, such as the closing of opened connections or resources in a module. Its {{Code|close()}} method will be called after the XQuery expression has been fully evaluated.
The internal properties of functions can be assigned via annotations:
* Java functions can only be executed by users with [[User_Management|Admin permissions]]. You may can annotate a function with {{Code|@Requires(<Permission>)}} to also make it accessible to users with less fewer privileges.* Java code is treated as ''non-deterministic'', as its behavior cannot be predicted by the XQuery processor. You may annotate a function as {{Code|@Deterministic}} if you know that it will have no side-effects and will always yield the same result.
* Java code is treated as ''context-independent''. If a function accesses the query context, it should be annotated as {{Code|@ContextDependent}}
* Java code is treated as ''focus-independent''. If a function accesses the current context item, position or size, it should be annotated as {{Code|@FocusDependent}}
public class ContextModule extends QueryModule implements QueryResource {
/**
* Returns the name of the logged -in user.
* @return user string
*/
Please visit the XQuery 3.0 specification if you want to get more insight into
[httphttps://www.w3.org/TR/xpath-functions-3031/#properties-of-functions function properties]. ==Updates== The {{Code|@Updating}} annotation can be applied to mark Java functions that perform write or update operations: <syntaxhighlight lang="java"> @Updating public void backup() { // ... }</syntaxhighlight> An XQuery expression will be handled as an [[XQuery Update#Updating Expressions|updating expression]] if it calls an updating Java function. In contrast to XQuery update operations, the Java code will immediately be executed, but the result will be cached as if {{Function|Update|update:output}} was called. The annotation is particularly helpful if combined with a lock annotation.
==Locking==
{{Mark|Updated By default, a Java function will be executed in parallel with Version 9other code.4:}} Single annotation for read and write locksIf a Java function performs sensitive operations, it is advisable to explicitly lock the code.
By default, ===Java Locks=== Java provides a Java function will handful of mechanism to control the execution of code. The concurrent execution of functions can be executed in parallel avoided with other codethe {{Code|synchronized}} keyword. For more complex scenarios, the Lock, Semaphore and Atomic classes can be brought into play.  ===XQuery Locks=== If a Java function performs sensitive operations, it is advisable you want to explicitly lock synchronize the execution of your code. This with BaseX locks, you can be realized with a lock take advantage of the {{Code|@Lock}} annotation:
<syntaxhighlight lang="java">
</syntaxhighlight>
When If an XQuery expression calls the Java invokes {{Code|write()}} function, every any other query that calls {{Code|write()}} or {{Code|read()}} needs to wait for the query to be finished. If The {{Code|read()}} is called, only those function can be run in parallel; whereas queries are will be queued that call if {{Code|write()}}is called.
More details on parallel query execution concurrent querying can be found in the article on [[Transaction Management]].
==Data Types==
===Conversion to Java=== Before Java code is executed, the arguments are converted to Java values, depending on the addressed function or constructor parameters. The accepted Java types and the original XQuery types are depicted in the second and first column of the table below. If a numeric value is supplied for which no exact matching is defined, it is cast to the appropriate type unless it exceeds its limits. The following two function calls are equivalent: <syntaxhighlight lang="xquery">(: exact match :)Q{String}codePointAt('ABC', xs:int(1)),(: xs:byte and xs:integer casts :)Q{String}codePointAt('ABC', xs:byte(1)),Q{String}codePointAt('ABC', 1)</syntaxhighlight> ===Conversion to XQuery=== By default, Java values with the most common types (as shown in the second and third column of the table) are converted to XQuery values. All other values are returned as ''Java items'', which are function items with a wrapped Java value. The results of constructor calls are mapped always returned as followsJava items. The conversion of the wrapped Java value to XQuery is enforced by invoking the function item: Values in {{Code|Iterator}} and {{Code|Iterable}} instances (Lists, Sets and Collections) are converted to items, and maps are converted to XQuery maps: <syntaxhighlight lang="xquery">declare namespace Scanner = 'java:java.util.Scanner';let $scanner := Scanner:new("A B C") => Scanner:useDelimiter(" ")return $scanner()</syntaxhighlight> If no conversion is defined, a string is returned, resulting from the {{Code|toString()}} method of the object. This method is also called is the string representation of a Java item is requested: <syntaxhighlight lang="xquery">(: returns the string representations of a HashMap and an ArrayList instance :)'Map: ' || Q{java.util.HashMap}new(),string(Q{java:java.util.ArrayList}new())</syntaxhighlight> The conversion can be further controlled with the {{Option|WRAPJAVA}} option. The following values exist:
{| class="wikitable"
|- valign="top"
! XQuery TypeValue! Description|- valign="top"| {{Code|some}}| The default: Java values of the most common types are converted, others are wrapped into Java items.|- valign="top"| {{Code|none}}| All Java values are converted. If no conversion is defined, a string is returned, resulting from the {{Code|toString()}} method.|- valign="top"| {{Code|all}}| Java values are wrapped into Java items (excluding those inheriting the internal type {{Code|org.basex.query.value.Value}}).|- valign="top"| {{Code|instance}}| If the method of a class instance was called, the Java value is ignored and the instance is wrapped into a Java item. Otherwise, the Java Typevalue is returned.
|- valign="top"
| {{Code|void}}
| Java values are ignored, and an empty sequence is returned instead.
|}
 
In the following example, the result of the first function – a char array – is wrapped and passed on to a {{Code|CharBuffer}} function. Without the option, the single-value array would be converted to an {{Code|xs:unsignedShort}} item and the second function call would fail:
 
<syntaxhighlight lang="xquery">
(: Without the pragma, the result of toChars would be converted to an xs:unsignedShort item, and the second function call would fail :)
 
(# db:wrapjava all #) {
Q{Character}toChars(xs:int(33))
=> Q{java.nio.CharBuffer}wrap()
}
</syntaxhighlight>
 
The next example demonstrates a use case for the {{Code|instance}} option:
 
<syntaxhighlight lang="xquery">
(: Thanks to the pragma, the function calls can be chained :)
 
declare namespace set = 'java:java.util.HashSet';
let $set := (# db:wrapjava instance #) {
set:new()
=> set:add('1')
=> set:add('2')
}
return $set()
</syntaxhighlight>
 
The {{Code|void}} option is helpful if side-effecting methods return values that do not contribute to the final result:
 
<syntaxhighlight lang="xquery">
(: Without the pragma, 100 booleans would be returned by the FLWOR expression :)
 
declare namespace set = 'java:java.util.HashSet';
let $set := set:new()
return (
(# db:wrapjava void #) {
for $i in 1 to 100
return set:add($set, $i)
},
$set()
)
</syntaxhighlight>
 
The irrelevant results could also be swallowed with {{Function|Profiling|prof:void}}.
 
{| class="wikitable"
|- valign="top"
! XQuery input
! Expected or returned Java type
! XQuery output
|- valign="top"
| <code>item()*</code> (no conversion)
| <code>org.basex.query.value.Value</code>
| <code>item()*</code> (no conversion)
|- valign="top"
| <code>empty-sequence()</code>
| <code>null</code>
| <code>empty-sequence()</code>
|- valign="top"
| <code>xs:string</code>, <code>xs:untypedAtomic</code>
| <code>String</code>
| <code>xs:string</code>
|- valign="top"| <code>Stringxs:unsignedShort</code>, | <code>char</code>, <code>Character</code>| <code>xs:unsignedShort</code>
|- valign="top"
| <code>xs:boolean</code>
| <code>boolean</code>, <code>Boolean</code>
| <code>xs:boolean</code>
|- valign="top"
| <code>xs:byte</code>
| <code>byte</code>, <code>Byte</code>
| <code>xs:byte</code>
|- valign="top"
| <code>xs:short</code>
| <code>short</code>, <code>Short</code>
| <code>xs:short</code>
|- valign="top"
| <code>xs:int</code>
| <code>int</code>, <code>Integer</code>
| <code>xs:int</code>
|- valign="top"
| <code>xs:integer</code>, <code>xs:long</code>
| <code>long</code>, <code>Long</code>
| <code>xs:integer</code>
|- valign="top"
| <code>xs:unsignedLong</code>
| <code>java.math.BigInteger</code>
| <code>xs:unsignedLong</code> (lossy)
|- valign="top"
| <code>xs:decimal</code>
| <code>java.math.BigDecimal</code>
| <code>xs:decimal</code>
|- valign="top"
| <code>xs:float</code>
| <code>float</code>, <code>Float</code>
| <code>xs:float</code>
|- valign="top"
| <code>xs:double</code>
| <code>double</code>, <code>Double</code>
|- valign="top"| <code>xs:decimal</code>| <code>java.math.BigDecimal</code>|- valign="top"| <code>xs:integer</code>| <code>java.math.BigIntegerdouble</code>
|- valign="top"
| <code>xs:QName</code>
| <code>javax.xml.namespace.QName</code>
| <code>xs:QName</code>
|- valign="top"
| <code>xs:anyURI</code>
| <code>java.net.URI</code>, <code>java.net.URL</code>
| <code>xs:anyURI</code>
|- valign="top"
| <code>xs:date</code>
| <code>javax.xml.datatype.XMLGregorianCalendar</code>
| <code>xs:date</code>
|- valign="top"
| <code>xs:duration</code>
| <code>javax.xml.datatype.Duration</code>
| <code>xs:duration</code>
|- valign="top"
| <code>node()</code>
| <code>org.w3c.dom.Node</code>
| <code>node()</code>
|- valign="top"
| <code>array(xs:boolean)</code>
| <code>boolean[]</code>
| <code>xs:boolean*</code>
|- valign="top"
| ''empty sequence''<code>array(xs:string)</code>| <code>String[]</code>| <code>xs:string*</code>|- valign="top"| <code>array(xs:unsignedShort)</code>| <code>char[]</code>| <code>xs:unsignedShort*</code>|- valign="top"| <code>array(xs:short)</code>| <code>short[]</code>| <code>xs:short*</code>|- valign="top"| <code>array(xs:int)</code>| <code>int[]</code>| <code>xs:int*</code>|- valign="top"| <code>array(xs:integer)</code>, <code>array(xs:long)</code>| <code>long[]</code>| <code>xs:integer*</code>|- valign="top"| <code>array(xs:float)</code>| <code>float[]</code>| <code>xs:float*</code>|- valign="top"| <code>array(xs:double)</code>| <code>double[]</code>| <code>xs:double*</code>|- valign="top"| <code>Object[]</code> (others)| <code>item()*</code>| <code>array(*)</code> (others)|- valign="top"| <code>map(*)</code>| java.util.HashMap| <code>nullWrapped Java object</code>
|}
=Changelog=
 
; Version 9.6
* Updated: Java Bindings revised (new mappings, Java functiom items, {{Option|WRAPJAVA}} option).
; Version 9.4
* Added: Annotation for [[#Updates|updating functions]].
* Updated: Single annotation for read and write locks.
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu