/***************************************
 *                                     *
 *  JBoss: The OpenSource J2EE WebOS   *
 *                                     *
 *  Distributable under LGPL license.  *
 *  See terms of license at gnu.org.   *
 *                                     *
 ***************************************/

package org.jboss.spring.callback;

import org.jboss.spring.support.SpringInjectionSupport;

import javax.ejb.PostActivate;
import javax.ejb.PostConstruct;
import javax.ejb.PrePassivate;
import javax.ejb.PreDestroy;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Injects Spring beans on postConstruction and postActivation.
 * Sets all non serializable, non transient fields to null before passivation.
 *
 * @see SpringInjectionSupport
 *
 * @author <a href="mailto:ales.justin@genera-lynx.com">Ales Justin</a>
 */
public class SpringCallbackListener extends SpringInjectionSupport {

    @PostConstruct
    public void postConstruct(Object bean) throws Throwable {
        inject(bean);
    }

    @PostActivate
    public void postActivate(Object bean) throws Throwable {
        inject(bean);
    }

    @PrePassivate
    public void prePassivate(Object bean) throws Throwable {
        Field[] fields = getAllFields(bean);
        for(Field f : fields) {
            boolean isSerializable = Serializable.class.isAssignableFrom(f.getType());
            boolean isTransient = Modifier.isTransient(f.getModifiers());
            if (!isSerializable && !isTransient) {
                f.setAccessible(true);
                f.set(bean, null);
            }
        }
    }

    @PreDestroy
    public void preDestroy(Object bean) throws Throwable  {
    }

}
