/*
 * 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.connectors.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.sun.logging.LogDomains;
import java.util.logging.*;

/**
 * A simple class to get the properties of a ConnectionDefinition class , that
 * could be overridden by the administrator during deployment.
 * 
 * @author Sivakumar Thyagarjan
 */
public class ConnectionDefinitionUtils {

    static Logger _logger= LogDomains.getLogger(LogDomains.RSR_LOGGER);

    /**
	 * Gets the properties of the Java bean connection definition class that
	 * have setter methods defined
	 * 
	 * @param connectionDefinitionClassName
	 *                     The Connection Definition Java bean class for which
	 *                     overrideable properties are required.
	 * @return A Set of properties that have a setter method defined in the
	 *                Connection Definition class
	 */
    public static Set getConnectionDefinitionProperties(String connectionDefinitionClassName) {
        HashSet propertySet= new HashSet();
        try {
            Method[] methods=
                Thread.currentThread().getContextClassLoader().loadClass(connectionDefinitionClassName).getMethods();
            for (int i= 0; i < methods.length; i++) {
                //Method starts with "set" and has only one parameter and has
                // a
                // valid argument
                if (isValidSetterMethod(methods[i])) {
                    String name= methods[i].getName();
                    String propertyName=
                        name.substring(
                            (name.indexOf("set") + "set".length()),
                            name.length());
                    propertySet.add(propertyName);
                }
            }
        } catch (SecurityException e) {
            handleException(e);
        } catch (ClassNotFoundException e) {
            handleException(e);
        }
        return propertySet;
    }

    private static boolean isValidSetterMethod(Method method) {
        return (
            (method.getName().startsWith("set"))
                && (method.getParameterTypes().length == 1)
                && (isValidArgumentType(method)));
    }

    private static boolean isValidArgumentType(Method method) {
        Class[] parameters= method.getParameterTypes();
        boolean isValid= true;
        for (int i= 0; i < parameters.length; i++) {
            Class param= parameters[i];
            if (!(param.isPrimitive() || param.equals(String.class)))
                return false;
        }
        return isValid;
    }

    /**
	 * Gets the properties of the Java bean connection definition class that
	 * have setter methods defined and the default values as provided by the
	 * Connection Definition java bean developer.
	 * 
	 * @param connectionDefinitionClassName
	 *                     The Connection Definition Java bean class for which
	 *                     overrideable properties are required.
	 * @return Map [property, defaultValue]
	 */
    public static Map getConnectionDefinitionPropertiesAndDefaults(String connectionDefinitionClassName) {
        Set s= getConnectionDefinitionProperties(connectionDefinitionClassName);
        HashMap hm= new HashMap();
        Class connectionDefinitionClass;
        try {
            connectionDefinitionClass=
                Thread.currentThread().getContextClassLoader().loadClass(connectionDefinitionClassName);
            Object obj= connectionDefinitionClass.newInstance();
            for (Iterator iter= s.iterator(); iter.hasNext();) {
                String property= (String) iter.next();
                Object defaultVal= null;
                try {
                    Method m=
                        connectionDefinitionClass.getMethod(
                            "get" + property,
                            new Class[] {});
                    defaultVal= m.invoke(obj, new Object[] {});
                    //ignore these exceptions. Some drivers have a setter but
                    // no getters for properties [example the password property
                    // in the OracleDataSource
                } catch (NoSuchMethodException e) {
                    //ignore
                } catch (IllegalArgumentException e) {
                    //ignore
                } catch (InvocationTargetException e) {
                    //ignore
                }
                //If the property does not have a corresponding getter method,
                // a null is placed as the default value.
                hm.put(property, defaultVal);
            }
        } catch (ClassNotFoundException e) {
            handleException(e);
        } catch (InstantiationException e) {
            handleException(e);
        } catch (IllegalAccessException e) {
            handleException(e);
        } catch (SecurityException e) {
            handleException(e);
        }
        return hm;
    }

    private static void handleException(Exception ex) {
        ex.printStackTrace();
        _logger.log(
            Level.SEVERE,
            "Exception while trying to find properties ",
            ex.getMessage());
    }

    //test code
    public static void main(String[] args) {

        //oracle.jdbc.xa.client.OracleXADataSource
        //com.pointbase.jdbc.jdbcDataSource
        Map m=
            ConnectionDefinitionUtils
                .getConnectionDefinitionPropertiesAndDefaults(
                "sun.jdbc.odbc.ee.DataSource");

        for (Iterator iter= m.keySet().iterator(); iter.hasNext();) {
            String element= (String) iter.next();
            System.out.println(element + " : " + m.get(element));
        }
    }
}
