úterý 15. února 2011

Oracle Like Decode in JasperReports

Oracle SQL has a nice function DECODE. I am using Java Beans data source for JasperReports and sometimes I have missed such a function in JasperReports expressions. One can achieve the same functionality by a ternary operator ? :. But it is not nice for more complicated conditions. So I have created my own Java decode:
public static Object decode(Object value, Object... arg) {
  if (arg == null) {
    return value;
  }
  int n = arg.length;
  for (int i = 0; i < n; i+=2) {
    int j = i + 1;
    if (j >= n) {
      // only the default remains
      return arg[i];
    }
    if (equal(value, arg[i])) {
      return arg[j];
    }
  }
  // no match found, no default is specified
  return value;
}
Then import it into JasperReports *.jrxml report by:
<import value="static com.mypackage.MyClass.decode"/>
And use it in the report like:
"" + decode(count, 0, "no one", 1, "one", 2, "two", "too many: " + count);