Wednesday, 4 January 2012

A Simple Property Viewer with Reflection and ZK

Sometimes I need to display a POJO’s properties/attributes. These POJOs may contain dozens of properties making it tedious to invoke all the getXxx() methods. So Java Reflection is a perfect candidate for such a use case.
In the following example, the LoginResponse class contains dozens of fields that I want to display. The formatMethodName() method beautifies the getXxx() method names into more human user friendly names.
import java.lang.reflect.Method;
import com.laws.acc.ws.*;
import com.laws.acc.model.*;

LoginResponse loginResponse=AccSoapClientProxy.getLoginResponse();
void populateRows() {  
 if(loginResponse!=null) {
  Method[] methods = LoginResponse.class.getDeclaredMethods();
  for(int i=0; i<methods.length; i++) {
   
   
   Method method=methods[i];
   //Object arglist[]={};
   if(method.getName().startsWith("get")) {
    Row row=new Row();
    Label label=new Label(formatMethodName(method.getName()));
    label.setStyle("font-style: italic;");
    label.setParent(row);
    new Label(method.invoke(loginResponse, null).toString()).setParent(row);
    row.setParent(rows);
   }
  }
 }
}
/**
 * turn strings such as 'getUserName' into 'User Name'
 */
private String formatMethodName(String name) {
 // the method name should start with 'get' followed by the property name
 // otherwise, ignore the method.
 if(name==null || name.length()<4) return null;
 StringBuffer sb=new StringBuffer();
 
 // skip the first 3 characters, they are 'get'
 for(int i=3; i<name.length(); i++) {
  char ch = name.charAt(i);
  if(i>3 && ch>='A' && ch<='Z') {
   sb.append(" ");
  }
  sb.append(ch);
 }
 return sb.toString().replace("Id", "ID").replace("Dt", "Timestamp").replace("Lre", "LRE").replace("Mvno", "MVNO");
 
}
The GUI component I am using is a ZK Grid with each row showing a property value.


 
// put the above java code here.

 

populateRows();

Server Error 500 on Saturday Lotto!

I tried to check my New Year’s eve NSW Saturday Lotto results on their official website, and one group of my numbers consistently resulted in server error 500.

Try this: http://www.nswlotteries.com.au/cgi-bin/results.pl?numlookup=1&game=satlotto&draw=3177&num1=4&num2=37&num3=1&num4=2&num5=3&num6=6

It turns out that as long as the group of numbers only match the supplementary numbers and nothing else, then it will result in errors. In the above example, the actual result of the Lotto draw was: 7, 8, 28, 33, 38, 41 with supplementary numbers 4 and 37.