5/27/2011

A generic approach to Liferay Services

Do you sometimes have to know what´s in the liferay databases ? But you can´t always access the database because you need VPN, URL connection strings etc etc etc ? Here is my approach, that you may or may not use. But please talk to your admins and bosses first ;) I implemented a generic approach to query the Liferay database using the Reflection API of Java.

It basically does nothing but to retrieve all objects of a Service, call all getters and display the data. My approach consists of two parts: A java class doing the string generation and a JSP displaying the data.

public String createTable(List<T> o) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

StringBuilder builder = new StringBuilder();
builder.append("<table><tr>");
Method[] methods = o.get(0).getClass().getMethods();
Object[] myArray = new Object[0];
//WRITE HEADER
for (Method meth : methods) {
  String name = meth.getName();
  Type[] typeParameters = meth.getGenericParameterTypes();
  if ((name.startsWith("get") && (typeParameters.length == 0))) {
  builder.append("<td>" + name.substring(3) + "</td>");
  }
}
builder.append("</tr>");
//WRITE CONTENT
for (Object myObject : o) {
  builder.append("<tr>");
  for (Method meth : methods) {
  String name = meth.getName();
  Type[] typeParameters = meth.getGenericParameterTypes();
  if ((name.startsWith("get") && (typeParameters.length == 0))) {
   builder.append("<td>" + meth.invoke(myObject, myArray)+ "</td>");
  }
}
builder.append("</tr>");

}

builder.append("</tr></table>");
return builder.toString();

}

If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.