/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * 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: JStatefulInputStream.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.ejb21;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.rmi.server.RemoteStub;

import javax.ejb.Handle;
import javax.ejb.HomeHandle;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.objectweb.util.monolog.api.BasicLevel;

/**
 * Extends ObjectInputStream because we want to enable resolveObject.
 * This class is very related to JStatefulOutputStream
 */
public class JStatefulInputStream extends ObjectInputStream {

    private JStatefulSwitch jss;

    /**
     * Constructor.
     * @throws IOException
     */
    public JStatefulInputStream(InputStream in, JStatefulSwitch jss) throws IOException {
        super(in);
        TraceEjb.ssfpool.log(BasicLevel.DEBUG, "constructor");
        enableResolveObject(true);
        this.jss = jss;
    }

    /**
     * We must care about some object types. See EJB spec. 7.4.1
     * @param obj serialized field
     * @return resolved object
     */
    protected Object resolveObject(Object obj) throws IOException {
        Object ret;

        if (obj instanceof HomeHandle) {
            // HomeHandle -> EJBHome
            TraceEjb.ssfpool.log(BasicLevel.DEBUG, "HomeHandle");
            ret = ((HomeHandle)obj).getEJBHome();
        } else if (obj instanceof Handle) {
            // Handle -> EJBObject
            TraceEjb.ssfpool.log(BasicLevel.DEBUG, "Handle");
            ret = ((Handle)obj).getEJBObject();
        } else if (obj instanceof JWrapper) {
            int type = ((JWrapper) obj).getType();
            switch (type) {
                case JWrapper.LOCAL_ENTITY:
                    TraceEjb.ssfpool.log(BasicLevel.DEBUG, "JEntityLocal");
                    String jndiname = (String) ((JWrapper) obj).getObject();
                    Object pk = ((JWrapper) obj).getPK();
                    JEntityLocalHome lhome = (JEntityLocalHome) JLocalHome.getLocalHome(jndiname);
                    ret = lhome.findLocalByPK(pk);
                    break;
                case JWrapper.LOCAL_HOME:
                    TraceEjb.ssfpool.log(BasicLevel.DEBUG, "JLocalHome");
                    String jname = (String) ((JWrapper) obj).getObject();
                    ret =  JLocalHome.getLocalHome(jname);
                    break;
                case JWrapper.USER_TX:
                    // UserTransaction
                    // Should be outside transaction here.
                    TraceEjb.ssfpool.log(BasicLevel.DEBUG, "UserTransaction");
                    ret = jss.getStatefulContext().getUserTransaction();
                    break;
                case JWrapper.SESSION_CTX:
                    // SessionContext.
                    // Should be outside transaction here.
                    TraceEjb.ssfpool.log(BasicLevel.DEBUG, "SessionContext");
                    ret = jss.getStatefulContext();
                    break;
                case JWrapper.NAMING_CONTEXT:
                    // ComponentContext
                    TraceEjb.ssfpool.log(BasicLevel.DEBUG, "ComponentContext");
                    String cname = (String) ((JWrapper) obj).getObject();
                    try {
                        InitialContext ictx = new InitialContext();
                        ret = ictx.lookup(cname);
                    } catch (NamingException e) {
                        TraceEjb.ssfpool.log(BasicLevel.ERROR, "Cannot retrieve NamingContext" + e);
                        throw new IOException("Cannot retrieve NamingContext");
                    }
                    break;
                case JWrapper.HANDLE:
                    TraceEjb.ssfpool.log(BasicLevel.DEBUG, "Handle");
                    
                    // Deserialize the Handle without JStatefulOutputStream
                    JWrapper theJWrapper = (JWrapper) obj;
                    byte ser[] = (byte[]) theJWrapper.getObject();
                    
                    ByteArrayInputStream bais = new ByteArrayInputStream(ser);
                    ObjectInputStream ois = new ObjectInputStream(bais);
                    Handle theHandle;

                    try {
                        theHandle = (Handle) ois.readObject();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        throw new IOException(e.getMessage());
                    }

                    ret = theHandle;
                    break;
                default:
                    TraceEjb.ssfpool.log(BasicLevel.DEBUG, "Other wrapped object");
                    ret = ((JWrapper) obj).getObject();
                    break;
            }
        } else if (obj instanceof RemoteStub) {
            // Remote Stub -> Remote
            TraceEjb.ssfpool.log(BasicLevel.DEBUG, "RemoteStub");
            // TODO
            ret = obj;
        } else {
            // Default -> keep the object as is.
            TraceEjb.ssfpool.log(BasicLevel.DEBUG, "Other");
            ret = obj;
        }
        return ret;
    }

    /**
     * Use the thread context class loader to resolve the class
     * @param v class to resolve
     * @return class resolved
     * @throws java.io.IOException thrown by the underlying InputStream.
     * @throws ClassNotFoundException thrown by the underlying InputStream.
     */
    protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException {
       TraceEjb.ssfpool.log(BasicLevel.DEBUG, v);
       ClassLoader cl = Thread.currentThread().getContextClassLoader();
       return cl.loadClass(v.getName());
    }

}
