
/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.util;

import java.util.*;
import java.lang.reflect.*;
import com.sun.enterprise.deployment.*;

/**
 * Utility class to calculate the list of methods required  to have transaction
 * attributes
 * 
 * @author  Jerome Dochez
 * @version 
 */
public class BeanMethodCalculator {
    
    
    public static Vector getPossibleCmpCmrFields(ClassLoader cl,
                                                 String className) 
        throws Exception {

        Vector fieldDescriptors = new Vector();
        Class theClass = cl.loadClass(className);

        // Start with all *public* methods
        Method[] methods = theClass.getMethods();

        // Find all accessors that could be cmp fields. This list 
        // will contain all cmr field accessors as well, since there
        // is no good way to distinguish between the two purely based
        // on method signature.
        for(int mIndex = 0; mIndex < methods.length; mIndex++) {
            Method next = methods[mIndex];
            String nextName = next.getName();
            int nextModifiers = next.getModifiers();
            if( Modifier.isAbstract(nextModifiers) ) {
                if( nextName.startsWith("get") &&
                    nextName.length() > 3 ) {
                    String field = 
                        nextName.substring(3,4).toLowerCase() + 
                        nextName.substring(4);
                    fieldDescriptors.add(new FieldDescriptor(field));
                }
            }
        }
        return fieldDescriptors;
    }
      
    public static Vector getMethodsFor(EjbDescriptor ejbDescriptor, ClassLoader classLoader) 
            throws ClassNotFoundException
    {
        Vector methods = new Vector();
        
        if (ejbDescriptor.isRemoteInterfacesSupported()) {
            addAllInterfaceMethodsIn(methods, classLoader.loadClass(ejbDescriptor.getHomeClassName()));
            addAllInterfaceMethodsIn(methods, classLoader.loadClass(ejbDescriptor.getRemoteClassName()));
        } 

        if (ejbDescriptor.isRemoteBusinessInterfacesSupported()) {
            for(String intf : ejbDescriptor.getRemoteBusinessClassNames()) {
                addAllInterfaceMethodsIn(methods, classLoader.loadClass(intf));
            }
        }

        if (ejbDescriptor.isLocalInterfacesSupported()) {
            addAllInterfaceMethodsIn(methods, classLoader.loadClass(ejbDescriptor.getLocalHomeClassName()));
            addAllInterfaceMethodsIn(methods, classLoader.loadClass(ejbDescriptor.getLocalClassName()));
        }

        if (ejbDescriptor.isLocalBusinessInterfacesSupported()) {
            for(String intf : ejbDescriptor.getLocalBusinessClassNames()) {
                addAllInterfaceMethodsIn(methods, classLoader.loadClass(intf));
            }
        }

        if (ejbDescriptor.hasWebServiceEndpointInterface()) {
            addAllInterfaceMethodsIn(methods, classLoader.loadClass(ejbDescriptor.getWebServiceEndpointInterfaceName()));
                                                                    
        }
        return methods;
    }
    
    private static void addAllInterfaceMethodsIn(Collection methods, Class c) {
        
        methods.addAll(Arrays.asList(c.getMethods()));
    }
    
    /**
     * @return a collection of MethodDescriptor for all the methods of my 
     * ejb which are elligible to have a particular transaction setting.
     */
    public static Collection getTransactionalMethodsFor(EjbDescriptor ejbDescriptor, ClassLoader loader)
        throws ClassNotFoundException, NoSuchMethodException
    {
        // only set if desc is a stateful session bean.  NOTE that 
        // !statefulSessionBean does not imply stateless session bean
        boolean statefulSessionBean = false;

        Vector methods = new Vector();
        if (ejbDescriptor instanceof EjbSessionDescriptor) {
            statefulSessionBean = 
                ((EjbSessionDescriptor) ejbDescriptor).isStateful();
            
	    // Session Beans
            if (ejbDescriptor.isRemoteInterfacesSupported()) {                
                Collection disallowedMethods = extractDisallowedMethodsFor(javax.ejb.EJBObject.class, sessionBeanMethodsDisallowed);
                Collection potentials = getTransactionMethodsFor(loader, ejbDescriptor.getRemoteClassName() , disallowedMethods);
                transformAndAdd(potentials, MethodDescriptor.EJB_REMOTE, methods);
            }
            
            if( ejbDescriptor.isRemoteBusinessInterfacesSupported() ) {
                
                for(String intfName : 
                        ejbDescriptor.getRemoteBusinessClassNames() ) {

                    Class businessIntf = loader.loadClass(intfName);
                    Method[] busIntfMethods = businessIntf.getMethods();
                    for (Method next : busIntfMethods ) {
                        methods.add(new MethodDescriptor
                                    (next, MethodDescriptor.EJB_REMOTE));
                    }
                }
            }

            if (ejbDescriptor.isLocalInterfacesSupported()) {
                Collection disallowedMethods = extractDisallowedMethodsFor(javax.ejb.EJBLocalObject.class, sessionLocalBeanMethodsDisallowed);
                Collection potentials = getTransactionMethodsFor(loader, ejbDescriptor.getLocalClassName() , disallowedMethods);
                transformAndAdd(potentials, MethodDescriptor.EJB_LOCAL, methods);
                
            }

            if( ejbDescriptor.isLocalBusinessInterfacesSupported() ) {
                
                for(String intfName : 
                        ejbDescriptor.getLocalBusinessClassNames() ) {

                    Class businessIntf = loader.loadClass(intfName);
                    Method[] busIntfMethods = businessIntf.getMethods();
                    for (Method next : busIntfMethods ) {
                        methods.add(new MethodDescriptor
                                    (next, MethodDescriptor.EJB_LOCAL));
                    }
                }
            }

            if (ejbDescriptor.hasWebServiceEndpointInterface()) {
                Class webServiceClass = loader.loadClass
                    (ejbDescriptor.getWebServiceEndpointInterfaceName());
                
                Method[] webMethods = webServiceClass.getMethods();                
                for (int i=0;i<webMethods.length;i++) {
                    methods.add(new MethodDescriptor(webMethods[i],  
                                MethodDescriptor.EJB_WEB_SERVICE));
                    
                }
            }

        } else {
            // entity beans local interfaces
            String homeIntf = ejbDescriptor.getHomeClassName();
            if (homeIntf!=null) {                
 
                Class home = loader.loadClass(homeIntf);
                Collection potentials = getTransactionMethodsFor(javax.ejb.EJBHome.class, home);
                transformAndAdd(potentials, MethodDescriptor.EJB_HOME, methods);
                
                String remoteIntf = ejbDescriptor.getRemoteClassName();                
                Class remote = loader.loadClass(remoteIntf);
                potentials = getTransactionMethodsFor(javax.ejb.EJBObject.class, remote);
                transformAndAdd(potentials, MethodDescriptor.EJB_REMOTE, methods);
            } 
            
            // enity beans remote interfaces
            String localHomeIntf = ejbDescriptor.getLocalHomeClassName();
            if (localHomeIntf!=null) { 
                Class home = loader.loadClass(localHomeIntf);
                Collection potentials = getTransactionMethodsFor(javax.ejb.EJBLocalHome.class, home);
                transformAndAdd(potentials, MethodDescriptor.EJB_LOCALHOME, methods);
                
                String remoteIntf = ejbDescriptor.getLocalClassName();                
                Class remote = loader.loadClass(remoteIntf);
                potentials = getTransactionMethodsFor(javax.ejb.EJBLocalObject.class, remote);
                transformAndAdd(potentials, MethodDescriptor.EJB_LOCAL, methods);                
            }
        }

        if( !statefulSessionBean ) {
            Class ejbClass = loader.loadClass(ejbDescriptor.getEjbClassName());
            if( ejbDescriptor.isTimedObject() ) {
                methods.add(ejbDescriptor.getEjbTimeoutMethod());
            }
        }

        return methods;
     }     
     
     private static Collection getTransactionMethodsFor(ClassLoader loader, String interfaceName, Collection disallowedMethods) 
        throws ClassNotFoundException
     {
         Class clazz = loader.loadClass(interfaceName);
         return getTransactionMethodsFor(clazz, disallowedMethods);
     }
     
     private static Collection getTransactionMethodsFor(Class interfaceImpl, Collection disallowedMethods) {
         Vector v = new Vector(Arrays.asList(interfaceImpl.getMethods()));
         v.removeAll(disallowedMethods);
         return v;
     }         
     
     private static Collection getTransactionMethodsFor(Class interfaceType, Class interfaceImpl) {
         Collection disallowedTransactionMethods = getDisallowedTransactionMethodsFor(interfaceType);
         return getTransactionMethodsFor(interfaceImpl, disallowedTransactionMethods);
     }
     
     private static Collection getDisallowedTransactionMethodsFor(Class interfaceType) {
         return extractDisallowedMethodsFor(interfaceType, getDisallowedMethodsNamesFor(interfaceType));                  
     }
     
     // from EJB 2.0 spec section 17.4.1
     private static Collection extractDisallowedMethodsFor(Class interfaceType, String[] methodNames) {
         
         Vector v = new Vector();
         // no disallowed methods for this interface 
         if (methodNames.length==0)
             return v;
         
         Method methods[] = interfaceType.getMethods();
         
         for (int i=0; i<methods.length; i++) {
            // all methods of the interface are disallowed
            if (methodNames[0].equals("*"))
                 v.addElement(methods[i]);             
            else if (Arrays.binarySearch(methodNames, methods[i].getName())>=0) 
                 v.addElement(methods[i]);
         }
         return v;
     }
     
     /**
      * utiliy method to transform our collection of Method objects into 
      * MethodDescriptor objects and add them to our global list of 
      * elligible methods
      * @param the collection of acceptable method objects
      * @param the method-intf identifier for those methods
      * @param the global list of MethodDescriptors objects 
      */
     private static void transformAndAdd(Collection methods, String methodIntf, Vector globalList) {
         
         for (Iterator itr = methods.iterator();itr.hasNext();) {
             Method m = (Method) itr.next();
             MethodDescriptor md = new MethodDescriptor(m, methodIntf);
             globalList.add(md);
         }
     }
     
     /**
      * @return the list of disallowed methods for a particular interface
      */
     private static String[] getDisallowedMethodsNamesFor(Class interfaceType) {
         return (String[]) getDisallowedMethodsNames().get(interfaceType);
     }
     
     /**
      * @return a Map of disallowed methods per interface type. The key to the 
      * map is the interface type (e.g. EJBHome, EJBObject), the value
      * is an array of methods names disallowed to have transaction attributes
      */
     protected static Map getDisallowedMethodsNames() {
         if (disallowedMethodsPerInterface==null) {
            disallowedMethodsPerInterface = new Hashtable();
            disallowedMethodsPerInterface.put(javax.ejb.EJBHome.class, entityBeanHomeMethodsDisallowed);
            disallowedMethodsPerInterface.put(javax.ejb.EJBObject.class, entityBeanRemoteMethodsDisallowed);
            disallowedMethodsPerInterface.put(javax.ejb.EJBLocalHome.class, entityBeanLocalHomeMethodsDisallowed);
            disallowedMethodsPerInterface.put(javax.ejb.EJBLocalObject.class, entityBeanLocalInterfaceMethodsDisallowed);
         } 
         return disallowedMethodsPerInterface;
     }
     
     private final static String entityBeanHomeMethodsDisallowed[] = { 
         "getEJBMetaData", "getHomeHandle" 
     };
     private final static String entityBeanRemoteMethodsDisallowed[] = {    
         "getEJBHome", "getHandle", "getPrimaryKey", "isIdentical"
     }; 
     private final static String entityBeanLocalHomeMethodsDisallowed[] = {};
     private final static String entityBeanLocalInterfaceMethodsDisallowed[] = {
        "getEJBLocalHome", "getPrimaryKey", "isIdentical"
     };
     
     private final static String sessionBeanMethodsDisallowed[] = {
         "*"
     };
     
     private final static String sessionLocalBeanMethodsDisallowed[] = {
         "*"
     };
     
     private static Map disallowedMethodsPerInterface;
     
}
