package org.strecks.lifecycle.impl;
import java.lang.reflect.Method;
import org.strecks.controller.internal.ActionBeanAnnotationReader;
import org.strecks.exceptions.ApplicationConfigurationException;
import org.strecks.lifecycle.LifecycleMethodAware;
import org.strecks.lifecycle.annotation.CloseMethod;
import org.strecks.lifecycle.annotation.InitMethod;
public class LifecycleMethodReader implements ActionBeanAnnotationReader<LifecycleMethodAware>
{
private Method initMethod;
private Method closeMethod;
public boolean readAnnotations(Class actionBeanClass)
{
Method[] methods = actionBeanClass.getMethods();
checkForInitMethod(actionBeanClass, methods);
checkForCloseMethod(actionBeanClass, methods);
return (initMethod != null || closeMethod != null);
}
private void checkForInitMethod(Class actionBeanClass, Method[] methods)
{
Method methodToReturn = null;
boolean found = false;
for (Method method : methods)
{
InitMethod annotation = method.getAnnotation(InitMethod.class);
if (annotation != null)
{
found = checkAnnotation(actionBeanClass, found, method);
if (found)
{
methodToReturn = method;
}
}
}
initMethod = methodToReturn;
}
private void checkForCloseMethod(Class actionBeanClass, Method[] methods)
{
Method methodToReturn = null;
boolean found = false;
for (Method method : methods)
{
CloseMethod annotation = method.getAnnotation(CloseMethod.class);
if (annotation != null)
{
found = checkAnnotation(actionBeanClass, found, method);if (found)
{
methodToReturn = method;
}
}
}
closeMethod = methodToReturn;
}
private boolean checkAnnotation(Class actionBeanClass, boolean found, Method method)
{
if (found)
{
throw new ApplicationConfigurationException(InitMethod.class.getSimpleName()
+ " annotation used more than once in the same class " + actionBeanClass);
}
final Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes != null && parameterTypes.length > 0)
{
throw new ApplicationConfigurationException(InitMethod.class.getSimpleName()
+ " annotation used with method " + method + " cannot have parameters");
}
final Class<?> returnType = method.getReturnType();
if (returnType != null && !returnType.equals(Void.TYPE))
{
throw new ApplicationConfigurationException(InitMethod.class.getSimpleName()
+ " annotation used with method " + method + " cannot have a return type");
}
found = true;
return found;
}
public void populateController(LifecycleMethodAware controller)
{
if (initMethod != null)
controller.setInitMethod(initMethod);
if (closeMethod != null)
controller.setCloseMethod(closeMethod);
}
public Method getInitMethod()
{
return initMethod;
}
public Method getCloseMethod()
{
return closeMethod;
}
}