Tuesday, 19 May 2009

Two Java Collection Utilities

Lately I stumbled upon two iteresting Java libraries which add search capabilities to Java collections: one adding SQL search and another adding XPath search syntax to an existing collection. I think it's cool - you can take a collection of Java objects and treat it in a high level way! I suppose they are implemented using introspection.

The first one is called JoSQL (http://josql.sourceforge.net/index.html) and can be used like this:
try {
Query q = new Query ();
q.parse(
"SELECT *" +
"FROM java.lang.String " +
"WHERE length <= :stringSize " +
"AND toString LIKE '%e%' " +
"ORDER BY length DESC");

q.setVariable ("stringSize", "5");
List<String> names = new ArrayList<String>();
String[] n = {
"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "pi", "chi"
};
Collections.addAll(names, n);

QueryResults qres = q.execute(names);
List res = qres.getResults();
}
catch(Exception e) ...
Here I got { "beta", "delta", "epsilon" } as result. The only problem I can see as far is that the library doesn't use generics. The other one is the somehow unintuitive way it's treating the "SELECT *" query. Nomally the JoSQL library treats a collection of Java objects as a table which columns are formed by the values returned by the class' methods. However, in case of a "SELECT *" query, we won't get all of the object's attributes, but just the whole object as it is. On the other side, it's the equivalent, isn't it.

The second one is called jXPath (http://commons.apache.org/jxpath/), and is part of the Apache project. You can use it like that:
    JXPathContext context = JXPathContext.newContext(employees);

Employee emp =
(Employee)context.getValue("/employees[name='Susan' and age=27]");
Pretty nifty, isn't it? But while SQL query syntax seemed obvious to me, the XPath search expressions seems plain ugly and non-intuitive. I don't know both SQL and X-Path very good, but I find myself always forgetting pretty everything about XPath while SQL gets stuck. Maybe because XPath is too low-level an too much a hack?

You can read in many blogs that the above libraries are pretty the same, but in reality, the XPath query syntax is better for hierarchical data, somehow like that:
    Employee emp =
(Employee)context.getValue("/departments/employees[name='Johnny']");
I assume you can do the equivalent in JoSQL, but you'd like to use joins, an that isn't that convenient for simple hierarchical structures like that above. So, in the end, maybe the XPath isn't so bad after all?

1 comment:

Stefan said...

XPath is cool and for some categories of tasks it is definitely the best solution!