/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: EasyBeansInvokerFactory.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.ws.cxf.easybeans;

import java.lang.reflect.Method;
import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;

import org.apache.cxf.jaxws.JAXWSMethodInvoker;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.invoker.Factory;
import org.apache.cxf.service.invoker.Invoker;
import org.ow2.easybeans.api.bean.EasyBeansSLSB;
import org.ow2.easybeans.api.bean.info.IWebServiceInfo;
import org.ow2.easybeans.container.session.stateless.StatelessSessionFactory;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;
import org.ow2.util.pool.api.PoolException;


/**
 * This class implements the Factory concept of CXF, that is
 * nicely mapped on the EasyBeans's Pool concept.
 */
public class EasyBeansInvokerFactory implements Factory {

    /**
     * Logger.
     */
    private Log logger = LogFactory.getLog(EasyBeansInvokerFactory.class);

    /**
     * EJB Factory.
     */
    private StatelessSessionFactory factory;

    /**
     * ejbCreate Method.
     */
    private Method ejbCreateMethod = null;

    /**
     * Creates an EasyBeansInvoker factory for the given factory.
     * @param factory the given session factory.
     */
     public EasyBeansInvokerFactory(final StatelessSessionFactory factory) {
         this.factory = factory;
     }

    /**
     * Creates the object that will be used for the invoke
     *
     * @return a new instance from the pool.
     * @throws Throwable
     */
    public Object create(final Exchange e) throws Throwable {
        EasyBeansSLSB statelessBean = factory.getPool().get();
        // SessionBean 2.x, needs to call the ejbCreate() method
        if (statelessBean instanceof SessionBean) {
            if (ejbCreateMethod == null) {
                ejbCreateMethod = statelessBean.getClass().getMethod("ejbCreate");
            }
            ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(statelessBean.getClass().getClassLoader());
            try {
                ejbCreateMethod.invoke(statelessBean);
            } finally {
                Thread.currentThread().setContextClassLoader(oldClassLoader);
            }
        }
        return statelessBean;
    }

    /**
     * Post invoke, this is called to allow the factory to release
     * the object, store it, etc...
     * @param o object created from the create method
     */
    public void release(final Exchange e, final Object o) {
        // SessionBean 2.x, needs to call the ejbRemove() method
        if (o instanceof SessionBean) {
            ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(o.getClass().getClassLoader());
            try {
                ((SessionBean) o).ejbRemove();
            } catch (EJBException e1) {
                logger.error("Unable to call the ejbRemove() method on the EJB 2.x Stateless session bean ''{0}''", o, e1);
            } catch (RemoteException e1) {
                logger.error("Unable to call the ejbRemove() method on the EJB 2.x Stateless session bean ''{0}''", o, e1);
            } finally {
                Thread.currentThread().setContextClassLoader(oldClassLoader);
            }
        }

        try {
            factory.getPool().release((EasyBeansSLSB) o);
        } catch (PoolException e1) {
            // Ignored Exception
        }
    }
}
