Archive for February, 2003

Interfacing to kdb+ from Java

Monday, February 17th, 2003

Retrieving data from kdb+ into Java is extremely simple.

The java driver for kdb+ resides in one file, c.java, and can be downloaded from www.kx.com/q/c. Don’t be put off when reading what is inside c.java - it is actually very straightforward. Most of the code is to serialize java objects into kdb+ objects, and vice versa. You can stick to the public methods, like the constructor, k, ks and close. In fact you need only be aware of 3 functions to query a server!

Essentially to query a server, one needs to open a connection, send a query, and then receive a response. We’ll go through that here:

public void test() {
c connection= null;
try
{
// open a connection using hostname, port, user and password
connection=new c(”localhost”,5001,”cskelton:xyz”);

// send a blocking query
Object result=connection.k(”fn”,new Integer(10),new Integer(20));

if( result instanceof Integer){
System.out.println( “Result is “+((Integer)result).intValue());
}
else {
System.err.println( “Unexpected result type received”);
}
}
catch( c.KException e){
System.err.println( “Server Reported Error: “+e.toString());
}
catch( java.io.IOException e){
System.err.println( “IOException: ” + e.getMessage());
}
finally{
if( connection != null)
{
try{
connection.close();
}
catch(java.io.IOException e){}
}
}
}

The above code opens a connection to the server, and invokes a function called fn, passing two parameters to it (2 integers, of values 10 and 20). The result from that call is stored in an Object result, which we then interrogate to see what type it is - we expect an Integer object, and if that’s what we receive, we print it and close the connection. On the server side we should create a suitable function to call, something like

fn:{x+y}

c.java only throws 2 types of checked exceptions - c.KException and java.io.IOException. KException is to indicate that the server itself has reported an error, and IOException is used to indicate a problem with the underlying network.

In the event of no errors or exceptions we should receive the Integer 30 as a result. If we cannot connect to the server, we print a message as

IOException: Connection refused

and if no function called fn exists on the server we would see

Server Reported Error: c$KException: fn

There are a few other errors that can happen, e.g. if authentication fails.

The methods k and ks inside c.java are for blocking and non-blocking queries. Typically you would use k(…) for your usual queries that you expect an immediate result from. If you are sending data to a kdb+ process, and do not need a confirmation that it has been processed you could use ks(…) instead.