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

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.*;
import com.sun.enterprise.config.ConfigContext;
import com.sun.enterprise.config.ConfigException;
import com.sun.enterprise.config.serverbeans.Applications;
import com.sun.enterprise.config.serverbeans.Domain;
import com.sun.enterprise.config.serverbeans.EjbModule;
import com.sun.enterprise.config.serverbeans.J2eeApplication;
import com.sun.enterprise.config.serverbeans.WebModule;
import com.sun.enterprise.server.ApplicationServer;
import com.sun.enterprise.server.PELaunch;
import com.sun.enterprise.server.ServerContext;
import com.sun.enterprise.util.SystemPropertyConstants;

public class ASClassLoaderUtil {
    private static Logger _logger = Logger.getAnonymousLogger();

    /** shared class loader of current server context */
    private static ClassLoader sharedCL;
    
    /**
     * Gets the classpath associated with a web module, suffixing libraries defined 
     * [if any] for the application
     * @param moduleId Module id of the web module
     * @return A <code>File.pathSeparator</code> separated list of classpaths
     * for the passed in web module, including the module specified "libraries"
     * defined for the web module.
     */
    public static String getWebModuleClassPath(String moduleId) {
            if (_logger.isLoggable(Level.FINE)) {
                _logger.log(Level.FINE, "module Id : " + moduleId);
            }

            StringBuilder classpath = new StringBuilder();
            if (Boolean.getBoolean(PELaunch.USE_NEW_CLASSLOADER_PROPERTY)) {
                //XXX: Instead of computing this everytime, add a method in PELaunch to return
                //this pre-formatted as a string
                List<String> cp = PELaunch.getSharedClasspath();
                for(String s:cp){
                    classpath.append(s);
                    classpath.append(File.pathSeparatorChar);
                }
            } else {
                classpath.append(System.getProperty("java.class.path"));
            }

            if (moduleId != null) {
                String specifiedLibraries = getLibrariesForWebModule(moduleId);
                URL[] libs = getLibraries(specifiedLibraries);
                if (libs == null)  {
                    if (_logger.isLoggable(Level.FINE)) {
                        _logger.log(Level.FINE, "classpath: " + classpath.toString());
                    }
                    return classpath.toString();
                }
  
                for (URL u : libs) {
                    classpath.append(u + File.pathSeparator);
                }
            }

            if (_logger.isLoggable(Level.FINE)) {
                _logger.log(Level.FINE, "Final classpath: " + classpath.toString());    
            }
            return classpath.toString();
    }
    
    /**
     * Gets the deploy-time "libraries" attribute  specified for a J2EE application (.ear file)
     * @param moduleId The module id of the J2EE application 
     * @return A comma separated list representing the libraries
     * specified by the deployer.
     */
    public static String getLibrariesForJ2EEApplication(String moduleId) {
        J2eeApplication app = null;
        try {
            app = getApplications().getJ2eeApplicationByName(moduleId);
            if(app == null) return null;
        } catch(ConfigException malEx) {
            _logger.log(Level.WARNING, "loader.cannot_convert_classpath_into_url",
                                                                                           moduleId);
            _logger.log(Level.WARNING,"loader.exception", malEx);            
        }
        return app.getLibraries();
    }

    /**
     * Gets the deploy-time "libraries" attribute specified for a web module (.war file)
     * @param moduleId The module id of the web module
     * @return A comma separated list representing the libraries
     * specified by the deployer.
     */
    public static String getLibrariesForWebModule(String moduleId) {
        WebModule app = null;
        try {
            app = getApplications().getWebModuleByName(moduleId);
            if(app == null) return null;
        } catch(ConfigException malEx) {
            _logger.log(Level.WARNING, "loader.cannot_convert_classpath_into_url",
                                                                                           moduleId);
            _logger.log(Level.WARNING,"loader.exception", malEx);            
        }

        String librariesStr  = app.getLibraries();
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, "app = " +  app + " library = " + librariesStr);
        }
        return librariesStr;
    }

    /**
     * Gets the deploy-time "libraries" attribute specified for an EJB module [EJB Jars]
     * @param moduleId The module id of the EJB module
     * @return A comma separated list representing the libraries
     * specified by the deployer.
     */
    public static String getLibrariesForEJBJars(String moduleId) {
        EjbModule app = null;
        try {
            app = getApplications().getEjbModuleByName(moduleId);
            if(app == null) return null;
        } catch(ConfigException malEx) {
            _logger.log(Level.WARNING, "loader.cannot_convert_classpath_into_url",
                                                                                           moduleId);
            _logger.log(Level.WARNING,"loader.exception", malEx);            
        }
        return app.getLibraries();
    }
    
    //Gets the Applications config bean from the application server's configcontext
    private static Applications getApplications() throws ConfigException {
        ConfigContext serverConfigCtx =  ApplicationServer.getServerContext().getConfigContext();
        Domain domain = ((Domain)serverConfigCtx.getRootConfigBean());
        return domain.getApplications();
    }
    
    /**
     * Utility method to obtain a resolved list of URLs representing the 
     * libraries specified for an application using the libraries 
     * application deploy-time attribute 
     * @param librariesStr The deploy-time libraries attribute as specified by 
     * the deployer for an application
     * @return A list of URLs representing the libraries specified for 
     * the application
     */
    public static URL[] getLibraries(String librariesStr) {
        if(librariesStr == null)
            return null;
        
        String [] librariesStrArray = librariesStr.split(",");
        if(librariesStrArray == null)
            return null;
        
        URL [] urls = new URL[librariesStrArray.length];
        //Using the string from lib and applibs requires admin which is 
        //built after appserv-core.
        String appLibsDir = System.getProperty(
                        SystemPropertyConstants.INSTANCE_ROOT_PROPERTY) 
                        + File.separator + "lib" 
                        + File.separator  + "applibs";
        
        int i=0;
        for(String libraryStr:librariesStrArray){
            try {
                File f = new File(libraryStr);
                if(!f.isAbsolute())
                    f = new File(appLibsDir, libraryStr);
                URL url = f.toURL();
                urls[i++] = url;
            } catch (MalformedURLException malEx) {
                _logger.log(Level.WARNING,
                        "loader.cannot_convert_classpath_into_url",
                        libraryStr);
                _logger.log(Level.WARNING,"loader.exception", malEx);
            }
        }
        return urls;
    }
    
    /**
     * Returns the shared class loader
     * @return ClassLoader
     */
    public static ClassLoader getSharedClassLoader() {
        if(sharedCL == null) {
            ServerContext sc = ApplicationServer.getServerContext();
            sharedCL = sc.getSharedClassLoader();            
        }
        return sharedCL;
    }
}
