Difference between revisions of "Java Bindings"

From BaseX Documentation
Jump to navigation Jump to search
m (Text replace - "{{Mono|" to "{{Code|")
Line 6: Line 6:
 
to directly access Java variables and execute code from XQuery. Java classes are identified by
 
to directly access Java variables and execute code from XQuery. Java classes are identified by
 
namespaces. The namespace URI must simply contain the fully qualified class name.
 
namespaces. The namespace URI must simply contain the fully qualified class name.
The URI can optionally be prefixed with the string {{Mono|java:}} to enforce that
+
The URI can optionally be prefixed with the string {{Code|java:}} to enforce that
 
the addressed code is written in Java.
 
the addressed code is written in Java.
  
Line 17: Line 17:
 
call static functions contained in that class.
 
call static functions contained in that class.
  
The following example uses Java’s {{Mono|Math}} class to return the cosine of an angle
+
The following example uses Java’s {{Code|Math}} class to return the cosine of an angle
by calling the static method {{Mono|cos()}}:
+
by calling the static method {{Code|cos()}}:
  
 
<pre class="brush:xquery">
 
<pre class="brush:xquery">
Line 33: Line 33:
  
 
The constructor of a class can be invoked by calling the virtual
 
The constructor of a class can be invoked by calling the virtual
function {{Mono|new()}}. Instance methods can then called by
+
function {{Code|new()}}. Instance methods can then called by
 
passing on the resulting Java object as first argument.
 
passing on the resulting Java object as first argument.
  
The following example writes 256 bytes to the file {{Mono|output.txt}}.
+
The following example writes 256 bytes to the file {{Code|output.txt}}.
First, a new {{Mono|FileWriter}} instance is created, and its
+
First, a new {{Code|FileWriter}} instance is created, and its
{{Mono|write()}} function is called in the next step:
+
{{Code|write()}} function is called in the next step:
  
 
<pre class="brush:xquery">declare namespace fw = "java.io.FileWriter";
 
<pre class="brush:xquery">declare namespace fw = "java.io.FileWriter";
Line 66: Line 66:
 
A new instance of the addressed class is created, which can then be accessed in the query body.
 
A new instance of the addressed class is created, which can then be accessed in the query body.
  
An example (the boolean values returned by {{Mono|set:add()}} are ignored):
+
An example (the boolean values returned by {{Code|set:add()}} are ignored):
  
 
<pre class="brush:xquery">
 
<pre class="brush:xquery">
Line 77: Line 77:
  
 
Advantages of this approach are:
 
Advantages of this approach are:
* imported code can be executed faster than instances created at runtime via {{Mono|new()}}.
+
* imported code can be executed faster than instances 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).
 
* 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).
  
Line 88: Line 88:
  
 
Java classes can be coupled more closely to the BaseX core library.
 
Java classes can be coupled more closely to the BaseX core library.
If an instantiated class inherits the abstract [https://github.com/BaseXdb/basex/blob/master/src/main/java/org/basex/query/QueryModule.java QueryModule] class of BaseX, it will get access to the {{Mono|context}} variable, which is an instance of the [https://github.com/BaseXdb/basex/blob/master/src/main/java/org/basex/query/QueryContext.java QueryContext] class. It provides access to all static and dynamic properties of the current query. Additionally, the default properties of functions can be changed via annotations:
+
If an instantiated class inherits the abstract [https://github.com/BaseXdb/basex/blob/master/src/main/java/org/basex/query/QueryModule.java QueryModule] class of BaseX, it will get access to the {{Code|context}} variable, which is an instance of the [https://github.com/BaseXdb/basex/blob/master/src/main/java/org/basex/query/QueryContext.java QueryContext] class. It provides access to all static and dynamic properties of the current 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 {{Mono|@Requires(<Permission>)}} to also make it accessible to users with less privileges.
+
* 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 ''non-deterministic'', as its behavior cannot be predicted by the XQuery processor. You may annotate a function as {{Mono|@Deterministic}} if you know that it will have no side-effects and will always yield the same result.
+
* 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 {{Mono|@ContextDependent}}
+
* 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 {{Mono|@FocusDependent}}
+
* 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 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:
 
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:

Revision as of 15:13, 26 May 2012

This article is part of the XQuery Portal. It demonstrates two ways to invoke Java code from XQuery, and (since Version 7.2.1) an extension to make Java code aware of the current context.

The Java Binding feature is an extensibility mechanism which enables developers to directly access Java variables and execute code from XQuery. Java classes are identified by namespaces. The namespace URI must simply contain the fully qualified class name. The URI can optionally be prefixed with the string java: to enforce that the addressed code is written in Java.

If the addressed Java code is not found in the classpath, it first needs to be installed in the Repository.

Namespace Declarations

Java classes can be declared via namespaces. The namespace can then be used to call static functions contained in that class.

The following example uses Java’s Math class to return the cosine of an angle by calling the static method cos():

declare namespace math = "java:java.lang.Math";
math:cos(xs:double(0))

The new Expanded QName notation of XQuery 3.0 can be applied as well to directly specify a namespace URI instead of the prefix:

Q{java.lang.Math}cos(xs:double(0))

The constructor of a class can be invoked by calling the virtual function new(). Instance methods can then called by passing on the resulting Java object as first argument.

The following example writes 256 bytes to the file output.txt. First, a new FileWriter instance is created, and its write() function is called in the next step:

declare namespace fw = "java.io.FileWriter";
let $file := fw:new('output.txt')
return (
  for $i in 0 to 255
  return fw:write($file, xs:int($i)),
  fw:close($file)
)

Function names with dashes will be rewritten to Java’s camel case notation:

XQuery: get-contents($x as xs:string) 
Java  : getContents(String x)

Note that Java code cannot be pre-compiled, and will often be evaluated slower than optimized XQuery code.

Module Imports

Template:Mark

Java code can also be integrated by importing classes as modules. A new instance of the addressed class is created, which can then be accessed in the query body.

An example (the boolean values returned by set:add() are ignored):

import module namespace set = "java.util.HashSet";
let $loop :=
  for $i in 1 to 10000
  return set:add($i)
return set:size()

Advantages of this approach are:

  • imported code can be executed faster than instances created at runtime via 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. This is also why the class must provide a constructor without no arguments.

Context-Awareness

Template:Mark

Java classes can be coupled more closely to the BaseX core library. If an instantiated class inherits the abstract QueryModule class of BaseX, it will get access to the context variable, which is an instance of the QueryContext class. It provides access to all static and dynamic properties of the current query. Additionally, the default properties of functions can be changed via annotations:

  • Java functions can only be executed by users with Admin permissions. You may annotate a function with @Requires(<Permission>) to also make it accessible to users with less privileges.
  • Java code is treated as non-deterministic, as its behavior cannot be predicted by the XQuery processor. You may annotate a function as @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 @ContextDependent
  • Java code is treated as focus-independent. If a function accesses the current context item, position or size, it should be annotated as @FocusDependent

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:

import module namespace context = 'org.basex.examples.query.ContextModule';

<context>{
  context:function-namespace()
}</context>,
<to-int>{
  try { context:to-int('abc') }
  catch * { 'Error in line', $err:line-number }
}</to-int>

The imported Java class is shown below:

package org.basex.examples.query;

import org.basex.query.*;
import org.basex.query.item.*;
import org.basex.util.*;

/**
 * This example is inherited from the {@link QueryModule} class.
 */
public class ContextModule extends QueryModule {
  /**
   * Returns the default function namespace.
   * @return default function namespace
   */
  @Requires(Permissions.NONE)
  @Deterministic
  @ContextDependent
  public Str functionNS() {
    return Str.get(context.sc.nsFunc);
  }

  /**
   * Converts the specified string to an integer.
   * @param value string representation
   * @return integer
   * @throws QueryException query exception
   */
  @Requires(Permissions.NONE)
  @Deterministic
  public int toInt(final String value) throws QueryException {
    try {
      return Integer.parseInt(value);
    } catch(NumberFormatException ex) {
      throw new QueryException(ex.getMessage());
    }
  }
}

The result will look as follows:

<context>http://www.w3.org/2005/xpath-functions</context>
<to-int>Error in line 6</to-int>

Please visit the XQuery 3.0 specification if you want to get more insight into function properties.

Changelog

Version 7.2.1

  • Added: import of Java modules, context awareness