2009-04-23

Avoid RuntimeException when null is passed to Ibator's example class.

Ibator's example classes are useful, but it throws RuntimeException when the passed value is null.
This is inconvenient when building a dynamic query conditions.

Instead of writing...

Criteria criteria = someExample.createCriteria();
if (condition1 != null)
  criteria.andCondition1EqualTo(condition1);
if (condition2 != null)
  criteria.andCondition2EqualTo(condition2);
if (condition3 != null)
  criteria.andCondition3EqualTo(condition3);
I want to write as...
Criteria criteria = someExample.createCriteria();
criteria.andCondition1EqualTo(condition1)
  .andCondition2EqualTo(condition2)
  .andCondition3EqualTo(condition3);

The following plugin replaces the line throwing RuntimeException with 'return;'.
So, null is just ignored silently.

import java.util.Iterator;
import java.util.List;

import org.apache.ibatis.ibator.api.IbatorPluginAdapter;
import org.apache.ibatis.ibator.api.IntrospectedTable;
import org.apache.ibatis.ibator.api.dom.java.InnerClass;
import org.apache.ibatis.ibator.api.dom.java.Method;
import org.apache.ibatis.ibator.api.dom.java.TopLevelClass;

public class ReplaceAddCriterionPlugin extends IbatorPluginAdapter
{
  public boolean validate(List<String> warnings)
  {
    return true;
  }

  @Override
  public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
    IntrospectedTable introspectedTable)
  {
    InnerClass innerClass = topLevelClass.getInnerClasses().get(0);
    Iterator<Method> it = innerClass.getMethods().iterator();
    while (it.hasNext())
    {
      Method m = it.next();
      String methodName = m.getName();
      if (methodName.startsWith("addCriterion"))
      {
        replaceRuntimeException(m);
      }
    }
    return true;
  }

  private void replaceRuntimeException(Method m)
  {
    List<String> bodyLines = m.getBodyLines();
    for (int i = 0; i < bodyLines.size(); i++)
    {
      if (bodyLines.get(i).contains("throw new RuntimeException"))
      {
        bodyLines.set(i, "return;");
        break;
      }
    }
  }
}