/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, 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/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 *
 * Contributor(s):
 *
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */
package org.jvnet.glassfish.comms.admin.gui.extensions.handlers;


import com.ericsson.ssa.dd.SipApplication;
import com.sun.appserv.management.config.DeployedItemRefConfig;

import com.sun.enterprise.ManagementObjectManager;
import com.sun.enterprise.Switch;
import com.sun.enterprise.admin.common.exception.ServerInstanceException;
import com.sun.enterprise.admin.mbeans.J2EEModule;
import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.BundleDescriptor;
import com.sun.enterprise.deployment.WebBundleDescriptor;
import com.sun.enterprise.deployment.WebComponentDescriptor;
import com.sun.enterprise.deployment.io.DescriptorConstants;
import com.sun.enterprise.deployment.pluggable.PluggableDeploymentInfo;
import com.sun.enterprise.instance.ExtensionModuleConfigManager;
import com.sun.enterprise.tools.admingui.util.AMXUtil;
import com.sun.enterprise.tools.admingui.util.GuiUtil;
import com.sun.enterprise.tools.admingui.util.JMXUtil;
import com.sun.enterprise.tools.admingui.util.TargetUtil;
import com.sun.enterprise.util.RelativePathResolver;

import com.sun.jsftemplating.annotation.Handler;
import com.sun.jsftemplating.annotation.HandlerInput;
import com.sun.jsftemplating.annotation.HandlerOutput;
import com.sun.jsftemplating.layout.descriptors.handler.HandlerContext;

import org.jvnet.glassfish.comms.admin.gui.extensions.util.SipTargetUtil;
import org.jvnet.glassfish.comms.admin.gui.extensions.util.SipUtil;

import java.io.File;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.management.Attribute;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.jvnet.glassfish.comms.deployment.backend.SipBundleDescriptor;
import org.jvnet.glassfish.comms.deployment.backend.SipApplicationBase;


/**
 *
 * @author irfan
 */
public class SipApplicationHandlers {
    public static final String[] sipModuleAttributeNames = new String[] {
            "object-type", "name", "directory-deployed", "libraries", "enabled",
            "availability-enabled", "module-type", "location", "description"
        };
    public static final String[] sipModuleDescriptorList = new String[] {
            DescriptorConstants.S1AS_WEB_DD_ENTRY,
            DescriptorConstants.WEB_DD_ENTRY,
            "WEB-INF" + File.separator + "sip.xml"
        };
    public static final String SIPAPP_CONVERGED_PROP = "isConverged";

    /** Creates a new instance of SipApplicationHandlers */
    public SipApplicationHandlers() {
    }

    /**
     *  <p> This handler returns the list of sip applications for populating the table.
     *  <p> Input  value: "name" -- Type: <code> java.lang.String</code></p>
     *  @param        context        The HandlerContext.
     */
    @Handler(id = "getDeployedSIPModulesInfo", input =  {
        @HandlerInput(name = "serverName", type = String.class, required = true)
        , @HandlerInput(name = "converged", type = Boolean.class, required = true)
    }
    , output =  {
        @HandlerOutput(name = "result", type = java.util.List.class)
    }
    )
    public static void getDeployedSIPModulesInfo(HandlerContext handlerContext) {
        Boolean showConverged = (Boolean) handlerContext.getInputValue(
                "converged");

        ObjectName[] sipModules = (ObjectName[]) JMXUtil.invoke(SipUtil.APP_OBJECT_NAME,
                "getExtensionModule", null, null);
        List sipApps = new ArrayList();

        for (ObjectName sipApp : sipModules) {
            String moduleType = (String) JMXUtil.getAttribute(sipApp,
                    "module-type");

            if (SipUtil.SIP_MODULE_TYPE.equals(moduleType)) {
                //OK this is a sip module. Extract all information
                HashMap sipAppAttributes = SipUtil.getAttributeValues(sipApp,
                        sipModuleAttributeNames);
                HashMap sipAppProps = SipUtil.getProperties(sipApp);
                Boolean isConvergedApp = Boolean.parseBoolean((String) sipAppProps.get(
                            SIPAPP_CONVERGED_PROP));

                HashMap oneRow = new HashMap();
                String enable = SipTargetUtil.getEnabledStatus(sipApp);
                oneRow.put("enabled", enable);

                String name = (String) sipAppAttributes.get("name");
                oneRow.put("name", name);

                /*String port = getPortForApplication(appConfig.getName());
                oneRow.put("port", port);*/
                oneRow.put(SIPAPP_CONVERGED_PROP, sipAppProps.get(SIPAPP_CONVERGED_PROP));

                if (isConvergedApp) {
                    //context root available only forr converged apps
                    oneRow.put("contextRoot", sipAppProps.get("contextRoot"));
                }

                oneRow.put("hasLaunch", false);
                oneRow.put("selected", false);

                //TODO Need to understand targets better
                //List<String> targets = TargetUtil.getDeployedTargets(appConfig, true);
                List<String> targets = TargetUtil.getDeployedTargets(name, true);

                if ((isConvergedApp && showConverged) ||
                        (!isConvergedApp && !showConverged)) {
                    sipApps.add(oneRow);
                }
            }
        }

        handlerContext.setOutputValue("result", sipApps);
    }

    /**
     *        <p> This handler returns the values for all the attributes of the Sip Application
     *  <p> Input  value: "name" -- Type: <code> java.lang.String</code></p>
     *  <p> Output value: "description" -- Type: <code>java.lang.String</code></p>
     *  <p> Output value: "enabled" -- Type: <code>java.lang.Boolean</code></p>
     *        @param        context        The HandlerContext.
     */
    @Handler(id = "getSipApplicationInfo", input =  {
        @HandlerInput(name = "name", type = String.class, required = true),
        @HandlerInput(name = "appType", type = String.class, required = true)
    },
    output =  {
        @HandlerOutput(name = "location", type = String.class),
        @HandlerOutput(name = "libraries", type = String.class),
        @HandlerOutput(name = "objectType", type = String.class),
        @HandlerOutput(name = "contextRoot", type = String.class),
        @HandlerOutput(name = "vs", type = String.class),
        @HandlerOutput(name = "description", type = String.class),
        @HandlerOutput(name = "availEnabled", type = Boolean.class),
        @HandlerOutput(name = "enabledString", type = String.class),
        @HandlerOutput(name = "enabled", type = Boolean.class),
        @HandlerOutput(name="hasContextRoot", type=Boolean.class)
    }
    )
    public static void getSipApplicationInfo(HandlerContext handlerContext) {
        String name = (String) handlerContext.getInputValue("name");
        String appType = (String) handlerContext.getInputValue("appType");

        ObjectName module = SipUtil.getSipApplication(SipUtil.APP_OBJECT_NAME, name);

        if (module != null) {
            HashMap moduleProps = SipUtil.getProperties(module);
            boolean isConverged = Boolean.parseBoolean((String)moduleProps.get(SIPAPP_CONVERGED_PROP));
            String contextRoot = "";
            if(isConverged) {
                contextRoot = (String) moduleProps.get("contextRoot");
            }
            handlerContext.setOutputValue("hasContextRoot", isConverged);
            handlerContext.setOutputValue("contextRoot", contextRoot);
            String availEnabled = (String) JMXUtil.getAttribute(module,
                    "availability-enabled");
            handlerContext.setOutputValue("availEnabled", availEnabled);

            if (!AMXUtil.supportCluster()) {
                //We need this only for PE, so hard code it "server"
                handlerContext.setOutputValue("vs",
                    TargetUtil.getAssociatedVS(name, "server"));
            }
        } else {
            //TODO: log error
            return;
        }

        handlerContext.setOutputValue("location",
            JMXUtil.getAttribute(module, "location"));
        handlerContext.setOutputValue("description",
            JMXUtil.getAttribute(module, "description"));
        handlerContext.setOutputValue("objectType",
            JMXUtil.getAttribute(module, "object-type"));

        if (AMXUtil.isEE()) {
            handlerContext.setOutputValue("enabledString",
                SipTargetUtil.getEnabledStatus(module));
        } else {
            //TODO Targets
            handlerContext.setOutputValue("enabled",
                SipTargetUtil.isApplicationEnabled(module, "server", false));
        }

        //TODO Need to get libraries
        /*String[] libArray = (String[]) ((Libraries)module).getLibraries();
        if (libArray != null){
            StringBuffer libs = new StringBuffer();
            for(int i=0; i< libArray.length; i++){
                libs.append("<br/>");
                libs.append(libArray[i]);
            }
            if (libs.length() > 1){
                handlerContext.setOutputValue("libraries", libs.substring(5));
            }
        }*/
    }

    @Handler(id = "saveSipApplicationInfo", input =  {
        @HandlerInput(name = "name", type = String.class, required = true)
        , @HandlerInput(name = "appType", type = String.class, required = true)
        , @HandlerInput(name = "description", type = String.class)
        , @HandlerInput(name = "contextRoot", type = String.class)
        , @HandlerInput(name = "enabled", type = Boolean.class)
        , @HandlerInput(name = "availEnabled", type = Boolean.class)
    }
    )
    public static void saveSipApplicationInfo(HandlerContext handlerContext) {
        String target = "server"; //TODO: Fix for EE
        String name = (String) handlerContext.getInputValue("name");
        String appType = (String) handlerContext.getInputValue("appType");

        try {
            ObjectName module = SipUtil.getSipApplication(SipUtil.APP_OBJECT_NAME, name);

            if (module != null) {
                HashMap properties = SipUtil.getProperties(module);
                boolean isConverged = Boolean.parseBoolean((String)properties.get(SIPAPP_CONVERGED_PROP));
                if(isConverged) {
                    String contextRoot = (String) handlerContext.getInputValue(
                            "contextRoot");

                    SipUtil.setProperty(module, "contextRoot", contextRoot);
                }

                if (AMXUtil.isEE()) {
                    Boolean ae = (Boolean) handlerContext.getInputValue(
                            "availEnabled");

                    if (ae != null) {
                        JMXUtil.setAttribute(module,
                            new Attribute("availability-enabled", ae));
                    }
                }
            }

            JMXUtil.setAttribute(module,
                new Attribute("description",
                    (String) handlerContext.getInputValue("description")));

            if (!AMXUtil.isEE()) {
                Boolean enabled = (Boolean) handlerContext.getInputValue(
                        "enabled");
                SipTargetUtil.setApplicationEnabled(module, "server", enabled, false);
            }
        } catch (Exception ex) {
            GuiUtil.handleException(handlerContext, ex);
        }
    }

    /**
    *        <p> This handler returns a list of Maps for populating the sub component table.
    *  <p> Input  value: "name" -- Type: <code> java.lang.String</code></p>
    *  <p> Input  value: "appType" -- Type: <code> java.lang.String</code></p>
    *        @param        context        The HandlerContext.
    */
    @Handler(id = "getSipSubComponents", input =  {
        @HandlerInput(name = "appName", type = String.class, required = true),
        @HandlerInput(name = "appType", type = String.class, required = true)
    },
    output =  {
        @HandlerOutput(name = "result", type = java.util.List.class)
    })
    
    public static String[] getSipSubComponents(HandlerContext handlerContext)
        throws MalformedObjectNameException {
        String appName = (String) handlerContext.getInputValue("appName");
        ObjectName sipApplication = (ObjectName) SipUtil.getSipApplication(SipUtil.APP_OBJECT_NAME,
                appName);
        List result = new ArrayList();
        String[] modules = null;

        try {
            BundleDescriptor desc = getDescrForStandAloneExtensionModule(appName);
            modules = getValidatedObjectNames(getExtensionModuleComponents(
                        (WebBundleDescriptor) desc));

            for (int i = 0; i < modules.length; i++) {
                HashMap oneRow = new HashMap();
                ObjectName on = new ObjectName(modules[i]);
                //Get the display field names from XML file
                oneRow.put("componentName", on.getKeyProperty("name"));
                String formattedType = SipUtil.getMessage(handlerContext,
                        on.getKeyProperty("j2eeType"), null);
                oneRow.put("componentType", formattedType);

                result.add(oneRow);
            }

            handlerContext.setOutputValue("result", result);
        } catch (ServerInstanceException ex) {
            GuiUtil.handleException(handlerContext, ex);
        }

        return modules;
    }

    /**
     *        <p> This method returns the deployment descriptors for a given app. </p>
     *
     *  <p> Output value: "descriptors" -- Type: <code>java.util.List</code>/</p>
     *        @param        context        The HandlerContext.
     */
    @Handler(id = "getSipDescriptors", input =  {
        @HandlerInput(name = "appName", type = String.class, required = true)
        , @HandlerInput(name = "includeSubComponent", type = Boolean.class)
    }
    , output =  {
        @HandlerOutput(name = "descriptors", type = List.class)
    }
    )
    public static void getSipDescriptors(HandlerContext handlerContext) {
        String appName = (String) handlerContext.getInputValue("appName");
        List list = new ArrayList();
        ObjectName sipApp = SipUtil.getSipApplication(SipUtil.APP_OBJECT_NAME, appName);
        String[] descriptors = null;
        Boolean includeSubComponent = (Boolean) handlerContext.getInputValue(
                "includeSubComponent");

        if (includeSubComponent == null) {
            includeSubComponent = false;
        }

        try {
            descriptors = getDescriptors(SipUtil.APP_OBJECT_NAME, appName);

            for (int i = 0; (descriptors != null) && (i < descriptors.length);
                    i++) {
                HashMap map = new HashMap();
                map.put("name", appName);
                map.put("moduleName", "");

                int index = descriptors[i].lastIndexOf(File.separator) + 1;
                map.put("descriptor", descriptors[i].substring(index));
                map.put("descriptorPath", descriptors[i]);
                list.add(map);
            }

            if (includeSubComponent) {
                String[] modules = getSipSubComponents(handlerContext);

                if (modules != null) {
                    for (int i = 0; i < modules.length; i++) {
                        String subComponentName = new ObjectName(modules[i]).getKeyProperty(
                                "name");
                        String[] subDesc = getDescriptors(appName,
                                subComponentName);

                        for (int j = 0;
                                (subDesc != null) && (j < subDesc.length);
                                j++) {
                            HashMap map = new HashMap();
                            map.put("name", appName);
                            map.put("moduleName", subComponentName);

                            int index = subDesc[j].lastIndexOf(File.separator) +
                                1;
                            map.put("descriptor", subDesc[j].substring(index));
                            map.put("descriptorPath", subDesc[j]);
                            list.add(map);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            GuiUtil.handleException(handlerContext, ex);
        }

        handlerContext.setOutputValue("descriptors", list);
    }

    /**
     *        <p> This handler takes in selected rows, and change the status of the app
     *  <p> Input  value: "selectedRows" -- Type: <code>java.util.List</code></p>
     *  <p> Input  value: "appType" -- Type: <code>String</code></p>
     *  <p> Input  value: "enabled" -- Type: <code>Boolean</code></p>
     *        @param        context        The HandlerContext.
     */
    @Handler(id = "changeSipAppStatus", input =  {
        @HandlerInput(name = "selectedRows", type = List.class, required = true)
        , @HandlerInput(name = "appType", type = String.class, required = true)
        , @HandlerInput(name = "enabled", type = Boolean.class, required = true)
    }
    )
    public static void changeSipAppStatus(HandlerContext handlerCtx) {
        List obj = (List) handlerCtx.getInputValue("selectedRows");
        boolean enabled = ((Boolean) handlerCtx.getInputValue("enabled")).booleanValue();

        //appType can be one of the following: application,webApp,ejbModule,connector
        String appType = (String) handlerCtx.getInputValue("appType");

        List selectedRows = (List) obj;

        try {
            for (int i = 0; i < selectedRows.size(); i++) {
                Map oneRow = (Map) selectedRows.get(i);
                String appName = (String) oneRow.get("name");
                ObjectName sipApp = SipUtil.getSipApplication(SipUtil.APP_OBJECT_NAME,
                        appName);

                if (sipApp == null) {
                    //Can't find the deployed app, don't do anything, except maybe log it in server.log
                } else {
                    List<String> targetList = TargetUtil.getDeployedTargets(appName,
                            true);

                    for (String target : targetList) {
                        //TargetUtil.setApplicationEnabled(appConfig, target, enabled);
                        DeployedItemRefConfig ref = TargetUtil.getDeployedItemRefObject(appName,
                                target);

                        if (enabled) {
                            JMXUtil.setAttribute(sipApp,
                                new Attribute("enabled", (Boolean) true));
                        }

                        if (ref != null) {
                            ref.setEnabled((Boolean) enabled);
                        }
                    }
                }

                if (AMXUtil.isEE()) {
                    String msg = GuiUtil.getMessage((enabled)
                            ? "msg.enableSuccessful" : "msg.disableSuccessful");
                    GuiUtil.prepareAlert(handlerCtx, "success", msg, null);
                } else {
                    String msg = GuiUtil.getMessage((enabled)
                            ? "msg.enableSuccessfulPE" : "msg.disableSuccessfulPE");
                    GuiUtil.prepareAlert(handlerCtx, "success", msg, null);
                }
            }
        } catch (Exception ex) {
            GuiUtil.handleException(handlerCtx, ex);
        }
    }

    /**
     *	<p> This handler returns the list of targets for populating the target table.
     *  <p> Input  value: "appName" -- Type: <code> java.lang.String</code></p>
     *  <p> Input  value: "appType" -- Type: <code> java.lang.String</code></p>
     *	@param	context	The HandlerContext.
     */
    @Handler(id="getSipApplicationTargetTableList",
        input={
            @HandlerInput(name="appName", type=String.class, required=true),
            @HandlerInput(name="appType", type=String.class, required=true)},
        output={
            @HandlerOutput(name="result", type=java.util.List.class)}
     )
    public static void getSipApplicationTargetTableList(HandlerContext handlerContext){
        
        String appName = (String)handlerContext.getInputValue("appName");
        String appType = (String)handlerContext.getInputValue("appType");
        List<String> targetList = TargetUtil.getDeployedTargets(appName, true);
        List result = new ArrayList();
        for(String target:  targetList){
            HashMap oneRow = new HashMap();
            oneRow.put("selected", false);
            oneRow.put("name", appName);
            oneRow.put("targetName",target);
            ObjectName module = SipUtil.getSipApplication(appName);
            if(module != null){  //appclients do not have enabled/lb-enabled attribute
                oneRow.put("enabled", Boolean.toString(
                        SipTargetUtil.isApplicationEnabled(module, target, false)));
                oneRow.put("lbEnabled", Boolean.toString(
                        SipTargetUtil.isApplicationEnabled(module, target, true)));
            }
            result.add(oneRow);
        }
        handlerContext.setOutputValue("result", result);
    }
    
    /**
     *	<p> This handler takes in selected rows, and change the status of the app
     *  <p> Input  value: "selectedRows" -- Type: <code>java.util.List</code></p>
     *  <p> Input  value: "appType" -- Type: <code>String</code></p>
     *  <p> Input  value: "enabled" -- Type: <code>Boolean</code></p>
     *	@param	context	The HandlerContext.
     */
    @Handler(id="changeSipTargetStatus",
    input={
        @HandlerInput(name="selectedRows", type=List.class, required=true),
        @HandlerInput(name="appType", type=String.class, required=true),
        @HandlerInput(name="appName", type=String.class, required=true),
        @HandlerInput(name="LB", type=Boolean.class),
        @HandlerInput(name="enabled", type=Boolean.class, required=true)})
        
    public static void changeSipTargetStatus(HandlerContext handlerContext) {
        
        //appType can be one of the following: application,webApp,ejbModule,connector
        String appType = (String)handlerContext.getInputValue("appType");
        String appName = (String)handlerContext.getInputValue("appName");
        ObjectName appConfig = SipUtil.getSipApplication(appName);
        if(appConfig == null){
            //Can't find the deployed app, don't do anything, except maybe log it in server.log
            return;
        }
        
        List obj = (List) handlerContext.getInputValue("selectedRows");
        boolean enabled = ((Boolean)handlerContext.getInputValue("enabled")).booleanValue();
        Boolean LB = (Boolean)handlerContext.getInputValue("LB");
        boolean forLB = (LB == null) ? false : LB.booleanValue();
        
        List selectedRows = (List) obj;
        try{
            for(int i=0; i< selectedRows.size(); i++){
                Map oneRow = (Map) selectedRows.get(i);
                String target = (String) oneRow.get("targetName");
                SipTargetUtil.setApplicationEnabled(appConfig, target, enabled, forLB);
            }
        }catch(Exception ex){
            GuiUtil.handleException(handlerContext, ex);
        }
    }
    
    @Handler(id="getApplicationExtensionComponents",
    output={
        @HandlerOutput(name="list", type=List.class)})
    public static void getApplicationExtensionComponents(HandlerContext handlerContext) {
        List components = new ArrayList();
        HashMap component = new HashMap();
        component.put("tooltip", "i18n.applications.enterpriseAppsToolTip");
        component.put("url", "/sip/applications/sipModules.jsf");
        component.put("imageURL", "/resource/images/application.gif");
        component.put("label", "sip.sipModules.label");
        components.add(component);
        component.clear();
        component.put("tooltip", "i18n.applications.webAppsToolTip");
        component.put("url", "/sip/applications/convergedSipModules.jsf");
        component.put("imageURL", "/resource/images/webModule.gif");
        component.put("label", "sip.convergedSipModules.label");
        components.add(component);
        
        handlerContext.setOutputValue("list", components);
    }
    
    //////////////////////////////
    protected static BundleDescriptor getDescrForStandAloneExtensionModule(
        String moduleName) throws ServerInstanceException {
        try {
            J2EEModule j2eeModule = new J2EEModule(moduleName);
            ExtensionModuleConfigManager manager = PluggableDeploymentInfo.getExtensionModuleDeployer(
                    j2eeModule.getModuleType()).getConfigManager();

            BundleDescriptor desc = (BundleDescriptor)manager.getRegisteredExtensionDescriptor(moduleName);
            if (desc == null) {
                Application app = manager.getExtensionDescriptor(moduleName, 
                        manager.getLocation(moduleName), true);
                desc = (BundleDescriptor) app.getBundleDescriptors().iterator().next();
            }
            return desc;
        } catch (Exception e) {
            throw new ServerInstanceException(e.getLocalizedMessage());
        }
    }

    protected static String[] getExtensionModuleComponents(
        WebBundleDescriptor bd) throws ServerInstanceException {
        ArrayList sArr = null;

        try {
            java.util.Set webDescriptors = bd.getWebDescriptors();
            ManagementObjectManager mom = Switch.getSwitch()
                                                .getManagementObjectManager();
            String moduleName = mom.getModuleName(bd);
            String applicationName = mom.getApplicationName(bd);
            WebComponentDescriptor wd = null;
            sArr = new ArrayList(webDescriptors.size());

            String j2eeType = null;
            String servletName = null;
            String cName = null;
            String dName = null;
            String sName = null;

            for (Iterator it = webDescriptors.iterator(); it.hasNext();) {
                wd = (WebComponentDescriptor) it.next();

                dName = wd.getDisplayName();
                sName = wd.getName();
                cName = wd.getCanonicalName();

                if ((dName != null) && (dName.length() > 0)) {
                    servletName = dName;
                } else if ((sName != null) && (sName.length() > 0)) {
                    servletName = sName;
                } else if ((cName != null) && (cName.length() > 0)) {
                    servletName = cName;
                } else {
                    servletName = "";
                }

                j2eeType = "Servlet";
                sArr.add("j2eeType=" + j2eeType + "," + "name=" +
                    servletName + "," + "ExtensionModule=" + moduleName + "," +
                    "J2EEApplication=" + applicationName);
            }
            
            if (bd instanceof SipBundleDescriptor) {
                SipApplicationBase sipApp = (SipApplication)((SipBundleDescriptor) bd).getSipApplication();
                if (sipApp != null) {
                    Iterator servlets = ((SipApplication)sipApp).getServlets().keySet().iterator();
                    while (servlets.hasNext()) {
                        servletName = (String) servlets.next();
                        if ((servletName == null) || (servletName.trim().length() == 0)) {
                            servletName = "";
                        }
                        j2eeType = "sip.sipApps.subcomponents.SipServletType";
                        sArr.add("j2eeType=" + j2eeType + "," + "name=" +
                            servletName + "," + "ExtensionModule=" + moduleName + "," +
                            "J2EEApplication=" + applicationName);
                    }
                }
            }
        } catch (Exception e) {
            throw new ServerInstanceException(e.getLocalizedMessage());
        }

        return (String[])sArr.toArray(new String[sArr.size()]);
    }

    private static String[] getValidatedObjectNames(String[] strArr)
        throws ServerInstanceException {
        // Append the domain name and server name to the input string array
        // and return it.
        String[] sArr = new String[strArr.length];

        try {
            for (int i = 0; i < strArr.length; i++) {
                sArr[i] = ("com.sun.appserv" + ":" + strArr[i] + "," +
                    "J2EEServer=" + "server");
            }
        } catch (Exception e) {
            throw new ServerInstanceException(e.getLocalizedMessage());
        }

        return sArr;
    }

    protected static String[] getDescriptors(String objectName, String appName)
        throws ServerInstanceException {
        ObjectName sipApp = SipUtil.getSipApplication(objectName, appName);
        String ddLocation = (String) JMXUtil.getAttribute(sipApp, "location");
        ddLocation = RelativePathResolver.resolvePath(ddLocation);

        ArrayList arrL = new ArrayList();
        String fileLocation = null;

        for (int i = 0; i < sipModuleDescriptorList.length; i++) {
            // if the descriptor exists then add to the list
            fileLocation = ddLocation + File.separator +
                sipModuleDescriptorList[i];

            try {
                File file = new File(fileLocation);

                if (file.exists()) {
                    arrL.add(fileLocation);
                }
            } catch (Exception e) {
                // continue with next file
            }
        }

        // return dd locations array
        if (arrL.size() > 0) {
            String[] strArr = new String[arrL.size()];

            for (int j = 0; j < arrL.size(); j++) {
                strArr[j] = (String) arrL.get(j);
            }

            return strArr;
        }

        return null;
    }

    
}
