Changes

Jump to navigation Jump to search
3,615 bytes added ,  18:42, 17 October 2017
This article is part of the [[XQuery|XQuery Portal]].It demonstrates two different ways to invoke Java code from XQuery, and an extension it presents extensions to make Java code aware of access the current query contextfrom Java.
The Java Binding feature is an extensibility mechanism which enables developers
to directly access Java variables and execute code from XQuery. Addressed Java classes are identified bynamespaces. The namespace URI code must simply contain either be contained in the fully qualified class name.The URI can optionally Java classpath, or it must be prefixed with located in the string {{Code|java:}} to enforce thatthe addressed code is written in Java[[Repository]].
If Please bear in mind that the addressed 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. =Identification= ==Classes== A Java class is not found identified by a namespace URI. The original URI is rewritten as follows: # The [[Repository#URI_Rewriting|URI Rewriting]] steps are applied to the URI.# Slashes in the classpathresulting URI are replaced with dots.# The last path segment of the URI is capitalized and rewritten to [https://en.wikipedia.org/wiki/CamelCase camel case]. The normalization steps are skipped if the URI is prefixed with {{Code|java:}}. See the following examples: * <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> ==Functions and Variables== Java 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, it first needs which is rewritten to camel case, identifies a variable or function of that class.* The middle dot character <code>·</code> ([http://www.fileformat.info/info/unicode/char/b7/index.htm &amp;#xB7;], a valid character in XQuery names, but not in Java) can beused to append exact Java parameter types to the function name. Class types must be referenced by their full path. installed in {| class="wikitable"|- valign="top"! Type! 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()</code>| <code>[https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode() object.hashCode()]</code>|- valign="top"| Function with types| <code>Q{java.lang.String}split·java.lang.String·int(';', 3)</code>| <code>[https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int- string.split(";", 3)]</code>|} As XQuery and Java have different type systems, XQuery arguments are converted to equivalent Java values, and the result of a Java function is converted back to an XQuery value (see [[Repository#Data Types|Data Types]]). If a Java function is not found, XQuery values may need to be cast 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=
Java classes can be declared via namespaces. The namespace can then be used tocall static functions contained in that class. Variables are represented asfunction with 0 parameters. The In the following example uses , Java’s {{Code|Math}} class to return is referenced. When executed, the query returns the cosine of an angleby calling the static method {{Code|cos()}}, and the value of π by addressing the staticvariable via {{Code|PI()}}:
<pre class="brush:xquery">
</pre>
The new With the [[XQuery 3.0#Expanded QNames|Expanded QName]] notation of XQuery 3.0,the namespace can directly be applied as well to directly specify a namespace URI instead of embedded in the prefixfunction call:
<pre class="brush:xquery">
</pre>
The constructor of a class can be invoked by calling the virtualfunction {{Code|new()}}. Instance methods can then called bypassing 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. The {{Code|java:}} prefix is omitted inthe URI:
<pre class="brush:xquery">declare namespace fw = "java.io.FileWriter";
</pre>
Function names with dashes will be rewritten to Java’s camel case notation: <pre class="brush:xquery">XQuery: get-contents($x as xs:string) If the result of a Java : getContents(String x)</pre> Strings with call contains invalid XML characters , it will be rejected by default. The validity check can be disabled by setting the [[Options#CHECKSTRINGS|CHECKSTRINGS]] option to false. The following query writes a file with a single 00-byte, which will then be successfully read via Java functions:
<pre class="brush:xquery">
</pre>
Note that Java code cannot be pre-compiled, and will often as such be evaluated slower than optimizedXQuery code.
=Module Imports=
Java code can also be integrated accessed by ''importing'' classes as modules.A new instance of the addressed class is will be created, which can then be accessed referenced in the query body.
An The following (side-effecting) example (returns the number of distinct values added to a hash set. The boolean values returned by {{Code|set:add()}} are ignored)will be swallowed:
<pre class="brush:xquery">
import module namespace set = "java:java.util.HashSet";let $loop prof:=void( for $i s in 1 to 10000("one", "two", "one") return set:add($is)return ),set:size()
</pre>
Advantages The advantages of this approach are:* is the execution of imported code can be executed faster classes is more efficient than the execution of instances that are created at runtime via {{Code|new()}}.* the work on class instances ensures that queries run in parallel will not cause any concurrency issues (provided that the class contains no static variables or functions). A drawback is that no arguments can be passed on to the class constructor.As a consequence, the import fails if the addressed class must provide a has no default constructor, but at least one constructor with no arguments.
=Context-Awareness=
{{Mark|Updated with Version 7.8}}: {{Code|context}} variable has been split into {{Code|queryContext}} and {{Code|staticContext}}. 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. Additionally, the default properties of functions can be changed via annotations:
* Java functions can only be executed by users with [[User_Management|Admin permissions]]. You may annotate a function with {{Code|@Requires(<Permission>)}} to also make it accessible to users with less privileges.
* 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}}
 
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 a query has been fully evaluated.
The following XQuery code invokes two Java methods. The first Java function retrieves information from the static query context, and the second one throws a query exception:
/**
* This example is inherited from inherits the {@link QueryModule} classand * implements the QueryResource interface.
*/
public class ContextModule extends QueryModule implements QueryResource {
/**
* Returns the name of the logged in user.
throw new QueryException(ex.getMessage());
}
}
 
@Override
public void close() {
// see description above
}
}
=Locking=
 
{{Mark|Introduced with Version 7.8:}}
By default, a Java function will be executed in parallel with other code. However, if a Java function performs sensitive write operations, it is advisable to explicitly lock the code. This can be realized via locking annotations:
If an XQuery expression is run which calls the Java {{Code|write()}} function, every other query that calls {{Code|write()}} or {{Code|read()}} needs to wait for the query to be finished. If a query calls the {{Code|read()}} function, only those queries are queued that call {{Code|write()}}, because this function is only annotated with a {{Code|read}} lock. More details on parallel query execution can be found in the article on [[Transaction Management]].
 
=Data Types=
 
The following table lists the mappings of XQuery and Java types:
 
{| class="wikitable"
|- valign="top"
! XQuery Type
! Java Type
|- valign="top"
| <code>xs:string</code>
| <code>String</code>, <code>char</code>, <code>Character</code>
|- valign="top"
| <code>xs:boolean</code>
| <code>boolean</code>, <code>Boolean</code>
|- valign="top"
| <code>xs:byte</code>
| <code>byte</code>, <code>Byte</code>
|- valign="top"
| <code>xs:short</code>
| <code>short</code>, <code>Short</code>
|- valign="top"
| <code>xs:int</code>
| <code>int</code>, <code>Integer</code>
|- valign="top"
| <code>xs:long</code>
| <code>long</code>, <code>Long</code>
|- valign="top"
| <code>xs:float</code>
| <code>float</code>, <code>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.BigInteger</code>
|- valign="top"
| <code>xs:QName</code>
| <code>javax.xml.namespace.QName</code>
|- valign="top"
| <code>xs:anyURI</code>
| <code>java.net.URI</code>, <code>java.net.URL</code>
|- valign="top"
| ''empty sequence''
| <code>null</code>
|}
=Changelog=
 
; Version 8.4
 
* Updated: Rewriting rules
 
; Version 8.0
 
* Added: {{Code|QueryResource}} interface, called after a query has been fully evaluated.
; Version 7.8
* Added: import of Java modules, context awareness
 
[[Category:XQuery]]
[[Category:API]]
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu