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.6Some more notes:}}
* 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 With {{Option|WRAPJAVA}} was added to control , it can be controlled 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 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>[https://www.fileformat.info/info/unicode/char/b7/index.htm ·]</code> (<code>&#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"
In the following example, 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 pre lang="'xquery"'>
declare namespace math = "java:java.lang.Math";
math:cos(xs:double(0)), math:PI()
</syntaxhighlightpre>
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 pre lang="'xquery"'>
Q{java:java.lang.Math}cos(xs:double(0))
</syntaxhighlightpre>
The constructor of a class can be invoked by calling the virtual function {{Code|new()}}. Instance methods can then called by passing on the resulting Java object as first argument. In the following example, 256 bytes are written to the file {{Code|output.txt}}. First, a new {{Code|FileWriter}} instance is created, and its {{Code|write()}} function is called in the next step:
<syntaxhighlight pre lang="'xquery"'>
declare namespace fw = 'java:java.io.FileWriter';
let $file := fw:new('output.txt')
fw:close($file)
)
</syntaxhighlightpre>
If the result of a Java call contains invalid XML characters, it will be rejected. The validity check can be disabled by setting {{Option|CHECKSTRINGS}} to false. In the example below, a file with a single {{Code|00}} byte is written, and this file will then be accessed by via Java functions:
<syntaxhighlight pre lang="'xquery"'>
declare namespace br = 'java:java.io.BufferedReader';
declare namespace fr = 'java:java.io.FileReader';
br:close($br)
)
</syntaxhighlightpre>
The option can also be specified via a pragma:
<syntaxhighlight pre lang="'xquery"'>
(# db:checkstrings #) {
br:new(fr:new('00.bin')) ! (br:readLine(.), br:close(.))
}
</syntaxhighlightpre>
=Module Imports=
A Java classes class can also be instantiated by ''importing'' them as a module: A new instance of the addressed class will be constructed, 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 the set is returned. As {{Code|set:add()}} returns boolean values, {{Function|Profiling|prof:void}} is used to swallow the values:
<syntaxhighlight pre lang="'xquery"'>
import module namespace set = "java:java.util.HashSet";
prof:void(
),
set:size()
</syntaxhighlightpre>
The execution of imported classes is more efficient than the execution of instances that have been created via {{Code|new()}}. In turn, no arguments can be supplied in the import statement, and the construction will only be successful if the class can be instantiated without arguments.
* Java functions can only be executed by users with [[User_Management|Admin permissions]]. You can annotate a function with {{Code|@Requires(<Permission>)}} to also make it accessible to users with fewer privileges.
* Java code is treated as ''non-deterministicnondeterministic'', 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}}
In the following code, information from the static query context is returned by the first function, and a query exception is raised by the second function:
<syntaxhighlight pre lang="'xquery"'>
import module namespace context = 'org.basex.examples.query.ContextModule';
element error { $err:description }
}
</syntaxhighlightpre>
The imported Java class is shown below:
<syntaxhighlight pre lang="java">
package org.basex.examples.query;
}
}
</syntaxhighlightpre>
The result will look as follows:
<syntaxhighlight pre lang="xml">
<user>admin</admin>
<error>Integer conversion failed: abc</error>
</syntaxhighlightpre>
Please visit the XQuery 3.0 specification if you want to get more insight into
The {{Code|@Updating}} annotation can be applied to mark Java functions that perform write or update operations:
<syntaxhighlight pre lang="java">
@Updating
public void backup() {
// ...
}
</syntaxhighlightpre>
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.
If you want to synchronize the execution of your code with BaseX locks, you can take advantage of the {{Code|@Lock}} annotation:
<syntaxhighlight pre lang="java">
@Lock("HEAVYIO")
public void read() {
// ...
}
</syntaxhighlightpre>
If an XQuery expression invokes {{Code|write()}}, any other query that calls {{Code|write()}} or {{Code|read()}} needs to wait for the query to be finished. The {{Code|read()}} function can be run in parallel; whereas queries will be queued if {{Code|write()}} is called.
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:
<pre 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)
</pre>
===Conversion to XQuery===
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 pre lang="'xquery"'>
declare namespace Scanner = 'java:java.util.Scanner';
let $scanner := Scanner:new("A B C") => Scanner:useDelimiter(" ")
return $scanner()
</syntaxhighlightpre>
If no conversion is defined, a string is returned, resulting from the {{Code|toString()}} method of the object. This method is also called is if the string representation of a Java item is requested:
<syntaxhighlight pre 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())
</syntaxhighlightpre>
The conversion can be further controlled with the {{Option|WRAPJAVA}} option. The following values exist:
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 pre lang="'xquery"'>
(: Without the pragma, the result of toChars would be converted to an xs:unsignedShort item, and the second function call would fail :)
=> Q{java.nio.CharBuffer}wrap()
}
</syntaxhighlightpre>
The next example demonstrates a use case for the {{Code|instance}} option:
<syntaxhighlight pre lang="'xquery"'>
(: Thanks to the pragma, the function calls can be chained :)
}
return $set()
</syntaxhighlightpre>
The {{Code|void}} option is helpful if side-effecting methods return values that do not contribute to the final result:
<syntaxhighlight pre lang="'xquery"'>
(: Without the pragma, 100 booleans would be returned by the FLWOR expression :)
$set()
)
</syntaxhighlightpre>
The irrelevant results could also be swallowed with {{Function|Profiling|prof:void}}.
* {{Code|a/little/example}} → {{Code|a/little/example}}
* {{Code|a:b:c}} → {{Code|a/b/c}}
Note that the mapping is not unique: Different URIs may result in the same path.
=Changelog=