Difference between revisions of "Java Bindings"

From BaseX Documentation
Jump to navigation Jump to search
Line 61: Line 61:
 
=Context-Awareness=
 
=Context-Awareness=
  
 +
{{Mark|Introduced with Version 7.2.1:}}
 +
 +
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 be enriched with two internal, context-dependent variables:
 +
 +
* {{Mono|context}} 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.
 +
* {{Mono|input}} is an instance of [https://github.com/BaseXdb/basex/blob/master/src/main/java/org/basex/util/InputInfo.java InputInfo]. It contains line/column and the original query and is mainly used for providing better error messages.
 +
 +
Below, two Java methods are shown that take advantage of the variables:
 +
 +
<pre class="brush:java">
 +
import org.basex.query.*;
 +
import org.basex.query.item.*;
 +
 +
/**
 +
* This example class contains two methods for demonstrating the use of the
 +
* {@link QueryModule} class.
 +
*/
 +
public class QueryModuleExample extends org.basex.query.QueryModule {
 +
  /**
 +
  * Returns the root expression of this query as string.
 +
  * @return root expression
 +
  */
 +
  public String rootExpression() {
 +
    return context.root.toString();
 +
  }
 +
 +
  /**
 +
  * Converts the specified string to an integer.
 +
  * @param value string representation
 +
  * @return integer
 +
  * @throws QueryException query exception
 +
  */
 +
  public int toInt(final String value) throws QueryException {
 +
    try {
 +
      return Integer.parseInt(value);
 +
    } catch(NumberFormatException ex) {
 +
      throw new QueryException(input, new QNm("FORM0001"), ex.getMessage());
 +
    }
 +
  }
 +
}
 +
</pre>
 +
 +
<pre class="brush:java">
 +
import module namespace context = 'java:org.basex.examples.query.ContextModule';
 +
 +
<context>{
 +
  context:function-namespace()
 +
}</context>,
 +
<error-code>{
 +
  try {
 +
    context:to-int('abc')
 +
  } catch * {
 +
    $err:code
 +
  }
 +
}</error-code>
 +
</pre>
  
 
=Changelog=
 
=Changelog=
Line 66: Line 122:
 
===Version 7.2.1===
 
===Version 7.2.1===
  
* Added: import of Java modules
+
* Added: import of Java modules, context awareness
  
 
[[Category:XQuery]]
 
[[Category:XQuery]]
 
[[Category:API]]
 
[[Category:API]]

Revision as of 17:00, 28 March 2012

This article is part of the Query 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 query 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 be of the form java:fully.qualified.ClassName.

Namespace Declarations

The following example uses Java’s Math class and returns the cosine of an angle. The cos() method can be directly called, as it is a static method:

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

The next example writes 256 bytes to the file output.txt. First, a new FileWriter instance is created: by calling the new() function, the class constructor is invoked. Instance methods are called by passing on the resulting Java object as first argument:

declare namespace fw = "java: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)
)

In general, it is recommended to use XQuery expressions and functions whenever possible, as Java code cannot be pre-compiled, and will often be evaluated slower than optimized XQuery code. Next, Java code can only be executed with admin permissions.

Module Imports

Template:Mark

Java code can also be integrated by importing classes as modules. In this case, 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: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 also implies that the class must provide a constructor without no arguments.

Context-Awareness

Template:Mark

If an instantiated class inherits the abstract QueryModule class of BaseX, it will be enriched with two internal, context-dependent variables:

  • context is an instance of the QueryContext class. It provides access to all static and dynamic properties of the current query.
  • input is an instance of InputInfo. It contains line/column and the original query and is mainly used for providing better error messages.

Below, two Java methods are shown that take advantage of the variables:

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

/**
 * This example class contains two methods for demonstrating the use of the
 * {@link QueryModule} class.
 */
public class QueryModuleExample extends org.basex.query.QueryModule {
  /**
   * Returns the root expression of this query as string.
   * @return root expression
   */
  public String rootExpression() {
    return context.root.toString();
  }

  /**
   * Converts the specified string to an integer.
   * @param value string representation
   * @return integer
   * @throws QueryException query exception
   */
  public int toInt(final String value) throws QueryException {
    try {
      return Integer.parseInt(value);
    } catch(NumberFormatException ex) {
      throw new QueryException(input, new QNm("FORM0001"), ex.getMessage());
    }
  }
}
import module namespace context = 'java:org.basex.examples.query.ContextModule';

<context>{
  context:function-namespace()
}</context>,
<error-code>{
  try {
    context:to-int('abc')
  } catch * {
    $err:code
  }
}</error-code>

Changelog

Version 7.2.1

  • Added: import of Java modules, context awareness