/*
 * 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.
 */

/*
 * DeploymentHandler.java
 *
 */

package com.sun.enterprise.tools.admingui.handlers;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;

import com.iplanet.jato.RequestContext;
import com.iplanet.jato.RequestManager;
import com.iplanet.jato.model.DefaultModel;
import com.iplanet.jato.model.Model;
import com.iplanet.jato.model.ModelControlException;
import com.iplanet.jato.view.*;
import com.iplanet.jato.view.html.SelectableGroup;
import com.iplanet.jato.view.html.TextField;
import com.iplanet.jato.view.html.OptionList;
import com.iplanet.jato.view.event.*;

import com.sun.web.ui.model.CCActionTableModelInterface;
import com.sun.web.ui.taglib.pagetitle.CCPageTitleTag;
import com.sun.web.ui.model.CCPropertySheetModelInterface;
import com.sun.web.ui.model.CCPropertySheetModel;
import com.sun.web.ui.common.CCI18N;


import javax.management.MBeanException;
import javax.management.ObjectName;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanInfo;
import javax.management.MBeanAttributeInfo;

import com.sun.enterprise.tools.guiframework.exception.FrameworkException;
import com.sun.enterprise.tools.guiframework.view.descriptors.CCPropertySheetDescriptor;
import com.sun.enterprise.tools.guiframework.model.ModelManager;
import com.sun.enterprise.tools.guiframework.view.DescriptorCCPageTitle;
import com.sun.enterprise.tools.guiframework.view.DescriptorContainerView;
import com.sun.enterprise.tools.guiframework.view.HandlerContext;
import com.sun.enterprise.tools.guiframework.view.descriptors.ViewDescriptor;
import com.sun.enterprise.tools.guiframework.view.descriptors.CCActionTableDescriptor;
import com.sun.enterprise.tools.guiframework.view.event.BeforeCreateEvent;
import com.sun.enterprise.tools.guiframework.view.DescriptorCCActionTable;

import com.sun.enterprise.tools.admingui.util.MBeanUtil;
import com.sun.enterprise.tools.admingui.util.Util;
import com.sun.enterprise.tools.admingui.util.JarExtract;
import com.sun.enterprise.tools.admingui.tree.IndexTreeNode;
import com.sun.enterprise.tools.admingui.tree.IndexTreeModelImpl;
import com.sun.enterprise.tools.admingui.tree.IndexTreeModel;
import com.sun.enterprise.tools.admingui.ConfigProperties;

import com.sun.enterprise.connectors.ConnectorRuntime;

import com.sun.enterprise.deployment.backend.DeploymentStatus;
import com.sun.enterprise.deployment.client.DeploymentFacility;
import com.sun.enterprise.deployment.client.DeploymentFacilityFactory;
import com.sun.enterprise.deployment.client.JESProgressObject;
import com.sun.enterprise.deployment.deploy.shared.AbstractArchive;
import com.sun.enterprise.deployment.deploy.shared.ArchiveFactory;
import com.sun.enterprise.deployment.util.DeploymentProperties;

//import com.sun.enterprise.tools.admingui.util.NamingConventions;
import com.sun.enterprise.appclient.jws.NamingConventions;

import com.sun.enterprise.tools.admingui.util.FileUtil;

/**
 *
 */
public class DeploymentHandler {

    // using DeploymentFacility API
     public void deploy(RequestContext ctx, HandlerContext handlerCtx) throws Exception {
	View view = handlerCtx.getView();
        if (!(view instanceof DescriptorContainerView)) {
            View parent = view.getParent();
            if (!(parent instanceof DescriptorContainerView)) {
		throw new FrameworkException(
		    "view is not DescriptorContainerView", null, view);
            } else {
                view = parent;
            }
        }
        if (view instanceof DescriptorCCPageTitle) {
	    view = view.getParent();
	}
	DescriptorContainerView descView = (DescriptorContainerView)view;
        
	Properties dProps = new Properties();
	ViewDescriptor vd = descView.getViewDescriptor();

	ArrayList displayNames = (ArrayList)handlerCtx.getInputValue("displayNames");
        ArrayList modelNames = (ArrayList)handlerCtx.getInputValue("attributeNames");

	for (int i = 0; i < displayNames.size(); i++) {
	    String displayValue = 
                (String)descView.getDisplayFieldValue((String)displayNames.get(i));
            if (displayValue==null) //to take care enable for PE & EE
                continue;
	    dProps.setProperty((String)modelNames.get(i), displayValue);
	}
        /* For java-web-start-enabled & libraries, need to convert the key first */
        String jws = dProps.getProperty("java-web-start-enabled");
        if (jws != null){
            dProps.setProperty(DeploymentProperties.DEPLOY_OPTION_JAVA_WEB_START_ENABLED_KEY, jws);
            dProps.remove("java-web-start-enabled");
        }
        
        String libraries = dProps.getProperty("libraries");
        if (libraries != null){
            dProps.setProperty(DeploymentProperties.DEPLOY_OPTION_LIBRARIES_KEY, libraries);
            dProps.remove("libraries");
        }
            
            
        dProps.setProperty("force", "false");
	//This is required only for PE.
	Boolean isTargetSupported = 
            ConfigProperties.getInstance().getTargetSupported();
	String type   = (String)handlerCtx.getInputValue("appType");
	if(isTargetSupported != null && !isTargetSupported.booleanValue() && (type.equals("war")||type.equals("ear"))){
	    String displayValue = 
                (String)descView.getDisplayFieldValue("virtualservers");
	    dProps.setProperty(DeploymentProperties.VIRTUAL_SERVERS, displayValue);
	}
	if((type.equals("war")||type.equals("ear")||type.equals("jar")) && 
		(isTargetSupported != null && isTargetSupported.booleanValue())) {
		String displayValue = 
		    (String)descView.getDisplayFieldValue("availabilityEnabled");
		dProps.setProperty(DeploymentProperties.AVAILABILITY_ENABLED, displayValue);
	}
        
	String objectName   = (String)handlerCtx.getInputValue("objectName");
	String methodName   = (String)handlerCtx.getInputValue("methodName");
        String[] targets = (String [])handlerCtx.getInputValue("targets");
            
        // to work around the bug# 6171271 on PC
        String location = (String)descView.getDisplayFieldValue("location");
        //char x1 = '\\';
        //char x2 = '/';
        Object raConfig = null;
        if (type.equals("rar")){
            ArrayList params = (ArrayList)handlerCtx.getInputValue("resourceAdapterParams");
            ArrayList types = (ArrayList)handlerCtx.getInputValue("resourceAdapterTypes");
            try {
                 raConfig = createResourceAdapter("com.sun.appserv:type=resources,category=config", 
                                "createResourceAdapterConfig", params, types);
            } catch (Exception ex) {
                //if config cannot be created, due to existence or other error, we just log it
                // but still continue with deployment.
                Util.logINFO("Deployment Handler createResourceConfig failed. "+ex.getMessage());
            }
        }
        try{
            invokeDeploymentFacility(targets, dProps, location);
        }catch (Exception ex){
            if (raConfig != null){
                //cleanup/remove Config if that is created here.
                String key = (String)MBeanUtil.getAttribute(raConfig.toString(), "resource-adapter-name");
                String[] types = new String[]{"java.lang.String"};
                Object[] params = new Object[]{key};
                try{
                    MBeanUtil.invoke("com.sun.appserv:type=resources,category=config", "removeResourceAdapterConfigByResourceAdapterName", params, types);
                }catch(Exception ex1){
                    Util.logINFO("Deployment Handler removeResourceAdapterConfig failed. "+ex1.getMessage());
                }
            }
            throw ex;
        }
        /* Set property if this rar is used for connecting to web service registry */
        if (raConfig != null) {
            String registryType = (String)handlerCtx.getInputValue("registryType");
            String propName = null;
            if (registryType.equals("uddi")) {
                propName = "com.sun.appserv.registry.uddi";
            } else if (registryType.equals("ebxml")) {
                propName = "com.sun.appserv.registry.ebxml";
            }
            if (propName != null) {
                Attribute attr = new Attribute(propName, "true");
                String[] types = new String[]{"javax.management.Attribute"};
                Object[] params = new Object[]{attr};
                MBeanUtil.invoke((ObjectName)raConfig, "setProperty", params, types);
            }
        }
    }
     
     public static boolean invokeDeploymentFacility(String[] targets, Properties props, String archivePath) 
     	throws Exception{
     	if(archivePath == null) {
     		//Localize this message.
     		throw new FrameworkException("archivePath is null");
     	}
     	if("true".equals(props.getProperty("force"))) {
            boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported().booleanValue();
            if (isTargetSupported){
     		//For redeployment target is domain by default for EE.
     		targets = new String[]{"domain"};
            }else{
                targets = new String[]{"server"};
            }
     	}
     	if(targets == null || targets.length == 0) {
     		//By default deploying to DAS to be in sync. with CLI.
     		targets = new String[]{"server"};
     	}
     	archivePath = archivePath.replace('\\', '/' );
        AbstractArchive archive = (new ArchiveFactory()).openArchive(archivePath); 
        DeploymentFacility df= DeploymentFacilityFactory.getLocalDeploymentFacility();
        JESProgressObject progressObject = null;
        
        progressObject = df.deploy(df.createTargets(targets), archive, null , props);  //null for deployment plan
        DeploymentStatus status = null;
        do {
            status = progressObject.getCompletedStatus();
            if(status == null) {
                try {
                    Thread.currentThread().sleep(1000);
                } catch(InterruptedException ie) {
                }
            }
        } while (status == null);
        boolean ret = checkDeployStatus(status, "deployment.warning");
     	return ret;
     }
     
     private static boolean checkDeployStatus(DeploymentStatus status, String warningIndex )throws  FrameworkException 
     {
        // parse the deployment status and retrieve failure/warning msg
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(bos);
        DeploymentStatus.parseDeploymentStatus(status, pw);
        byte[] statusBytes = bos.toByteArray();
        String statusString = new String(statusBytes);
        String bundle = "com.sun.enterprise.tools.admingui.resources.Resources";
        
         if (status!=null && status.getStatus() == DeploymentStatus.FAILURE){ 
             throw new FrameworkException(statusString);
         }
         //maybe we should also display this to the user, instead of just 'hidding' in the log file.
         if (status!=null && status.getStatus() == DeploymentStatus.WARNING){
             if (warningIndex != null)
                 Util.logINFO( Util.getMessage(bundle, warningIndex, null));
         }
         return true;
     }
     
    
    public void descriptorDisplay(RequestContext ctx, HandlerContext handlerCtx) {
	String fileName = (String)ctx.getRequest().getAttribute("fileName");
	String objectName = (String)ctx.getRequest().getAttribute("objectName");

	View view = handlerCtx.getView();
	DisplayField descriptorField = (DisplayField)view;
	
        String descriptors = (String)MBeanUtil.invoke(objectName, "getDeploymentDescriptor",
							    new Object[]{fileName}, new String[]{"java.lang.String"});
          
        descriptorField.setValue(descriptors);
    }
    
    public void beginDescriptorTitleDisplay(RequestContext ctx, HandlerContext handlerCtx) {
        CCPageTitleTag tag = (CCPageTitleTag)handlerCtx.getEvent().getSource();
        String fileName = (String)handlerCtx.getInputValue("filename");
        
        //If we want to display the full path file name, comment out the following if.
        if (fileName != null) {
            File f = new File(fileName);
            fileName = f.getName();
        }
        tag.setPageTitleText(fileName);
    }

    public void beginUploadPageTitleDisplay(RequestContext ctx, HandlerContext handlerCtx) {
        CCPageTitleTag tag = (CCPageTitleTag)handlerCtx.getEvent().getSource();
        String appType = (String)handlerCtx.getInputValue("applicationType");
        Boolean redeploy = (Boolean)handlerCtx.getInputValue("redeploy");
        String key = null;
        if (redeploy.booleanValue()) {
            key = "redeploy.PageTitle";
        } else {
            key = "upload.PageTitle";
        }
        HashMap map = new HashMap();
        map.put("war", Util.getMessage("upload.WebModule"));
        map.put("ear", Util.getMessage("upload.EnterpriseApplication"));
        map.put("jar", Util.getMessage("upload.EJBModule"));
        map.put("rar", Util.getMessage("upload.ConnectorModule"));
        map.put("all", Util.getMessage("upload.AppclientModule")); 
        map.put("mbean", Util.getMessage("upload.CustomMBean"));
        String mappedValue = (String)map.get(appType);
        String titleText = Util.getMessage(key, new Object[]{mappedValue});
        
        tag.setPageTitleText(titleText);
        if (appType.equals("all")) {
            //Setting it to jar for appclient module type.
            appType = "jar";
        }
        String helpText = "";
        if (appType.equals("mbean")){
            helpText = Util.getMessage("createCustomMBean.pageHelp");
        }else
            helpText = Util.getMessage("uploadPageHelp", new Object[]{appType, mappedValue});
            
        tag.setPageTitleHelpMessage(helpText);
    }

    public void extractJarFile(RequestContext ctx, HandlerContext handlerCtx) {
        String fileName = (String)handlerCtx.getInputValue("fileName");
        String domainRoot = (String)handlerCtx.getInputValue("domainRoot");
        
        if(fileName == null || domainRoot == null) {
                throw new FrameworkException("fileName, or domainRoot is null DeploymentHandlers.extractJarFile");
        }
        
        try {
            FileUtil.extractMbeanJarFile(domainRoot, fileName );
        }catch (IOException ex){
            throw new FrameworkException(ex);
        }

    }
    
    
    

    /* This is needed only for connector (rar) deployment. We've to work with Qingqing/vijay to fix this
     * in the new API. We've to discuss this with Binod/Siva in IEC also. */
    public void saveThreadPool(RequestContext ctx, HandlerContext handlerCtx) {
	String name = (String)handlerCtx.getInputValue("name");
	String objectName   = (String)handlerCtx.getInputValue("objectName");
	String threadPool   = (String)handlerCtx.getInputValue("threadPoolId");
	if (objectName == null) {
	    throw new FrameworkException("'objectName' is null in DeploymentHandler.saveThreadPool");
	}

	try {
	    Attribute attr = new Attribute("thread-pool-ids", threadPool);
	    MBeanUtil.setAttribute(objectName, attr);
	} catch (Exception ex) {
	    //might have been deployed from CLI.
	    //FIXME LATER. Directory deploy is broken, so not creating anymore. Commented on 06/10.
	   // createResourceAdapter(name, "com.sun.appserv:type=resources,category=config", 
				   // "createResourceAdapterConfig", threadPool);
	}
    }

    public void getVirtualservers(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
        if (!(view instanceof DescriptorContainerView)) {
            View parent = view.getParent();
            if (!(parent instanceof DescriptorContainerView)) {
		throw new FrameworkException("View is not a DescriptorContainerView!", null, view);
            }  else {
                view = parent;
            }
        }
        if (view instanceof DescriptorCCPageTitle) {
            view = view.getParent();
        }
        DescriptorContainerView descView = (DescriptorContainerView)view;
        String childName = (String)handlerCtx.getInputValue("childName");
	TextField textFieldChild = (TextField)descView.getChild(childName);
	
	String objectName = (String)handlerCtx.getInputValue("vsObjectName");
	String vsMethodName = (String)handlerCtx.getInputValue("vsMethodName");
	String vsList = "";

	Object[] vsObjectName = (Object[])
            MBeanUtil.invoke(objectName, vsMethodName, null, null);
	//hardcoding the name for now, may be we should get this from the xml file.
	String attributeName = "id";
	if(vsObjectName != null) {
	    for(int i =0; i < vsObjectName.length; i++) {
		String virtualservers = (String)
                    MBeanUtil.getAttribute(vsObjectName[i].toString(), attributeName);
		if(virtualservers != null && !(virtualservers.equals("__asadmin"))) {
		    vsList += virtualservers + ",";
		}
	    }
	}
	if (vsList.length() > 0) {
	    //stripping the last char
	    vsList = vsList.substring(0, vsList.length()-1);
	    textFieldChild.setValue(vsList);
	}
    }

    public void setThreadPoolID(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
	DescriptorContainerView descView = (DescriptorContainerView)view.getParent();
	String editKey = (String)descView.getDisplayFieldValue("editKey");
	String adapterObjectName = "com.sun.appserv:type=resource-adapter-config,category=config,resource-adapter-name="+editKey;
	try {
	    String threadPool = (String)MBeanUtil.getAttribute(adapterObjectName, "thread-pool-ids");
	    ((TextField)view).setValue(threadPool);
	} catch (Exception ex) {
	    //squelch, it's o.k if we don't get this attribute.
	}
    }
    
     /**
     *
     */
    public void loadResourceAdapterProperties(RequestContext ctx, HandlerContext handlerCtx) throws ModelControlException  {
	View view = handlerCtx.getView();
        ViewDescriptor desc = null;
        if (handlerCtx.getEvent() instanceof BeforeCreateEvent)
            desc = ((BeforeCreateEvent)handlerCtx.getEvent()).getViewDescriptor();
        else {
            DescriptorContainerView descView = (DescriptorContainerView)((ViewBase)view);
            desc = descView.getViewDescriptor();
        }
       
	CCActionTableModelInterface model = 
            (CCActionTableModelInterface)handlerCtx.getInputValue("propertiesModel");
        ((DefaultModel)model).clear();
        Object properties = handlerCtx.getInputValue("properties");
	
	if (properties == null) {
	    if (Util.isLoggableFINER()) {
		Util.logFINER("NO ATTRS FOUND!!");
	    }
	    //nothing to load..
            return;
	}
	
	else if(properties instanceof AttributeList) {
	    loadResourceAdapterProperties((AttributeList)properties, model);
	}
	else if(properties instanceof Map) {
	    loadResourceAdapterProperties((Map)properties, model);
	}
	else {
	    throw new FrameworkException("Unknown instance properties", desc, view);
	}
           
    }
    
    private void loadResourceAdapterProperties (AttributeList attrs, CCActionTableModelInterface model) throws ModelControlException  {
	// Log some info..
	StringBuffer buf = new StringBuffer();
        for(int rowNo = 0; rowNo < attrs.size(); rowNo++) {
            Attribute attr = (Attribute)attrs.get(rowNo);
            buf.append("!!! name = " + attr.getName() + " , value = " + attr.getValue()+"\n");
        }
	if (Util.isLoggableFINER()) {
	    Util.logFINER(buf.toString());
	}

	model.setRowSelectionType("none");
        model.beforeFirst();
        for (int rowNo = 0; rowNo < attrs.size(); rowNo++) {
            model.appendRow();
            Attribute attr = (Attribute)attrs.get(rowNo);
            model.setValue(PROPERTY_NAME, attr.getName());
            model.setValue(PROPERTY_VALUE, attr.getValue());
	}
    }
    
    private void loadResourceAdapterProperties (Map properties, CCActionTableModelInterface model) throws ModelControlException  {
	Set s = properties.keySet();
	Iterator iter = s.iterator();
	
	model.setRowSelectionType("none");
        model.beforeFirst();
	while (iter.hasNext()) {
	    Object key = iter.next();
	    model.appendRow();
            model.setValue(PROPERTY_NAME, key);
            model.setValue(PROPERTY_VALUE, properties.get(key));
	}
	
    }
    
    /**
     *	This method invokes ConnectorRuntime, and outputs the properties in request attribute.
     */
    public void getResourceAdapterProperties(RequestContext ctx, HandlerContext handlerCtx) {
	
	String location = (String)handlerCtx.getInputValue("location");
        if (location == null) {
            //if deployment failed, the page still needs to be repainted, and at this time,
            //location is gone and will be null.
            //we ignore it here so that the previouse deployment error message will show up.
            handlerCtx.setOutputValue("properties", null);
            return;
        }
        try{
           
	Map props = ConnectorRuntime.getRuntime().getResourceAdapterBeanProperties(location);
        //refer to bug#6212118.
        //The value of the key thats returned is the type, eg.class.java.lang.String, int, boolean etc
        //We don't want to display that to the user.
        Set s = props.keySet();
        Map newMap = new HashMap();
        for (Iterator iter = s.iterator(); iter.hasNext(); ) {
            newMap.put(iter.next(), "");
        }
            handlerCtx.setOutputValue("properties", newMap);
        }catch (Exception ex){
            //refer to bug#6278568. 
            Util.logSEVERE("Error in getting ResourceAdapter Properties ", ex);
            handlerCtx.setOutputValue("properties", null);
            return;
        }
    }
    
    /*
     * Adding this method for now to take care of directoryDeployment. We're not creating 
     * RAConfig in directory deployment.
     */
    
    public void getResourceAdapterPropertiesForEdit(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
        
        Object objectName   = handlerCtx.getInputValue("objectName");
        if (objectName == null) {
            throw new FrameworkException("'objectName' is null in DeploymentHandler.getResourceAdpaterPropertiesForEdit");
	}
        String methodName   = (String)handlerCtx.getInputValue("methodName");
        if (methodName == null) {
            throw new FrameworkException("'methodName' is null in DeploymentHandler.getResourceAdpaterPropertiesForEdit");
	}
        Object returnValue = null;
        try {
            
            returnValue = MBeanUtil.invoke(objectName.toString(), methodName, 
                    null, null);
            
        } catch (Exception ex) {
	    //squelch the Exception here, o.k for RAConfig.
        }
        handlerCtx.setOutputValue("value", returnValue);
    }

    public void createResourceAdapter(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
        
        Object objectName   = handlerCtx.getInputValue("objectName");
        if (objectName == null) {
            throw new FrameworkException("'objectName' is null in CommonHandlers.invokeMBean");
	}
        String methodName   = (String)handlerCtx.getInputValue("methodName");
        if (methodName == null) {
            throw new FrameworkException("'methodName' is null in CommonHandlers.invokeMBean");
	}
        ArrayList types     = (ArrayList)handlerCtx.getInputValue("types");
        ArrayList params    = (ArrayList)handlerCtx.getInputValue("params");
        
	createResourceAdapter(objectName, methodName, params, types);
    }
    
    private Object createResourceAdapter(Object objectName, String methodName, ArrayList params, ArrayList types) {
	Object[] paramsAndTypes = MBeanUtil.getParamsAndTypes(params, types);
	try {
            return MBeanUtil.invoke(objectName.toString(), methodName, 
                    (Object[])(paramsAndTypes[0]), (String[])(paramsAndTypes[1]));
            
        } catch (Exception ex) {
	    //squelch this here, due to cli inconsistency, and redeploy.
        }
        return null;
    }
    
    private void setResourceAdapterProperties(String name) {
	String objectName = "com.sun.appserv:type=resource-adapter-config,category=config,resource-adapter-name="+ name;
	Properties props = null;
	try {
	    //We've to make this call to an MBean. For now o.k.
	    props = ConnectorRuntime.getRuntime().getResourceAdapterConfigProps(name);
	}
	catch (Exception e) {
	    //O.K to squelch, due CLI issues.
	    Util.logINFO("Deployment Handler setResourceAdapterProperties:"+e.getMessage());
	    return;
	}
	Enumeration ee = props.propertyNames();
	
	while(ee.hasMoreElements()) {
	    Object key = ee.nextElement();
	    String[] type = new String[]{"javax.management.Attribute"};
	    Attribute attr = new Attribute(key.toString(), props.getProperty(key.toString()).toString());
            Object[] params = new Object[]{attr};
            MBeanUtil.invoke(objectName, "setProperty", params, type);
	}
	
    }
    
    public void applicationRefAction(RequestContext ctx, HandlerContext handlerCtx) {
    	View view = handlerCtx.getView();
    	DescriptorContainerView descView = (DescriptorContainerView)
    	    (((ViewBase)view).getParentViewBean());
    	ViewDescriptor vd = descView.getViewDescriptor();

    	//we may need to get the tabilChildName from the xml file.
        String tableChildName = (String)handlerCtx.getInputValue("tableChildName");
    	ViewDescriptor tableDescriptor = vd.getChildDescriptor(tableChildName);
    	if (tableDescriptor == null) {
    	    throw new FrameworkException("tableDescriptor is null", vd, view);
    	}
    	if (!(tableDescriptor instanceof CCActionTableDescriptor)) {
    	    throw new FrameworkException("tableDescriptor is of wrong type",
    		tableDescriptor, view);
    	}
    	CCActionTableModelInterface model = (CCActionTableModelInterface)handlerCtx.getInputValue("propertiesModel");
    	if (model == null) {
                throw new FrameworkException("PropertiesHandler.getModel: Parameter 'propertiesModel' not specified");
            }
        String editKeyValue = (String)handlerCtx.getInputValue("editKeyValue");
    	String action = (String)handlerCtx.getInputValue("action");
    	String methodName = (String)handlerCtx.getInputValue("methodName");
    	model.setRowSelectionType("multiple");
    	try {
    	    model.beforeFirst();
    	    while(model.next()) {
    		if (model.isRowSelected()) {
    		    String objectName = (String)model.getValue("objectName");
                    String target = (String)MBeanUtil.getAttribute(objectName, "name");
                    changeEnableStatus(editKeyValue, new String[] { target }, action);
    		    model.setRowSelected(false);
    		}
    	    }
    	} catch (Exception ex) {
            Util.logFINER("Error while enabling: " + vd.getName());
    	    throw new FrameworkException(ex);
        }
    	ContainerViewBase containerView = 
                (ContainerViewBase)(tableDescriptor.getView(ctx).getParent());
    	containerView.removeChild(tableDescriptor.getName());
    	((DefaultModel)model).clear();
    }
    
    
    /* This method is invoked when user clicks enable/disable/undeploy in the table. */
    public void actionClicked(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
	DescriptorContainerView descView = (DescriptorContainerView)
	    (((ViewBase)view).getParentViewBean());
	ViewDescriptor vd = descView.getViewDescriptor();
	String childName = (String)vd.getParameter("tableChildName");

	if (childName == null) {
	    throw new FrameworkException("childName not specified", vd, view);
	}
	ViewDescriptor tableDescriptor = vd.getChildDescriptor(childName);
	if (tableDescriptor == null) {
	    throw new FrameworkException("tableDescriptor is null", vd, view);
	}
	if (!(tableDescriptor instanceof CCActionTableDescriptor)) {
	    throw new FrameworkException("tableDescriptor is of wrong type",
		tableDescriptor, view);
	}
        String buttonClicked = (String)handlerCtx.getInputValue("ClickedAction");
	try {
            
	    if (buttonClicked.equalsIgnoreCase("undeploy")) {
                String type = (String)handlerCtx.getInputValue("AppType");
		undeploy(((CCActionTableDescriptor)tableDescriptor).getModel(), 
                    tableDescriptor, type);
	    }
	    else {
		doAction(((CCActionTableDescriptor)tableDescriptor).getModel(), 
                    tableDescriptor, buttonClicked);
	    }
	} catch (FrameworkException ex) {
	    throw new FrameworkException("Error while deleting from: '"+
		tableDescriptor.getName()+"'", ex, tableDescriptor, descView);
	}
    }

    private void doAction(CCActionTableModelInterface model, ViewDescriptor vd, String buttonClicked) {
	RequestContext ctx = RequestManager.getRequestContext();
        DeploymentFacility df= DeploymentFacilityFactory.getLocalDeploymentFacility();
        String defaultTarget = ConfigProperties.getInstance().getDefaultTarget();
        JESProgressObject progressObject = null;
        model.setRowSelectionType("multiple");
        try {
            model.beforeFirst();
            // from the model, get the child that has the needed value...
            while(model.next()) {
                if (model.isRowSelected()) {
                    enableDisableAll((String) model.getValue(NAME), buttonClicked);
                    model.setRowSelected(false);
                }
            }
        }catch (Exception ex) {
	    throw new FrameworkException("Error while " + buttonClicked + " : '"+
		vd.getName()+"'", ex, vd, null);
        }
	View view = vd.getView(ctx).getParent();
	ContainerViewBase descView = (ContainerViewBase)view;
	descView.removeChild(vd.getName());
	((DefaultModel)model).clear();
    }

    private void enableDisableAll(String appsName, String action)
    {
        RequestContext ctx = RequestManager.getRequestContext();
        Boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported();
	boolean targetSupported = (isTargetSupported == null) ? false : isTargetSupported.booleanValue();
        String defaultTarget = ConfigProperties.getInstance().getDefaultTarget();
        if (targetSupported){
            String[] params = new String[] {appsName};
            String[] types = new String[] {"java.lang.String"};
            ObjectName[] refs = (ObjectName[]) MBeanUtil.invoke("com.sun.appserv:type=applications,category=config" , "listReferencees", params, types); 
            int size = (refs==null ) ? 0 : refs.length;
            String[] targetList = new String[size];
            for(int i=0; i<size; i++){
                targetList[i] = (String)MBeanUtil.getAttribute(refs[i], "name");
            }
            changeEnableStatus(appsName, targetList, action);
        }else{
            changeEnableStatus(appsName, new String[] { defaultTarget }, action);
        }
    }
    
    static public void changeEnableStatus(String appsName, String[] targetList, String action ){
        if (targetList == null) return;
        //DeploymentFacility is not responsible for changing the enable/disable status of custom mbean
        //We need to handle it differently.
        Object[] params = new String[]{appsName};
        
        Integer type = (Integer) MBeanUtil.invoke("com.sun.appserv:type=applications,category=config", "getModuleType", params, new String[]{"java.lang.String"});
        if((type != null) && (type.intValue() == DisplayItemMapper.MODULE_MBEAN)){
            changeEnableStatusForMbean(appsName,targetList,action); 
            return;
        }
        
        boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported().booleanValue();
        DeploymentFacility df= DeploymentFacilityFactory.getLocalDeploymentFacility();
        JESProgressObject progressObject = null;
        if (action.equals("enable") || action.equals("true")){
            //when enabling a target, we always ensure that the application is enabled.
            if (isTargetSupported){
                if (getAppStatus(appsName, "domain").equals("false")){
                    String[] newTargetList = new String[targetList.length+1];
                    for(int i=0; i< targetList.length; i++){
                        newTargetList[i]=targetList[i];
                    }
                    newTargetList[targetList.length] = "domain";
                    targetList = newTargetList;
                }
            }
            progressObject = df.enable(df.createTargets(targetList), appsName);
        }else{
            progressObject = df.disable(df.createTargets(targetList), appsName);
        }
        DeploymentStatus status = df.waitFor(progressObject);
        checkDeployStatus(status, null);
    }
    
    static private void changeEnableStatusForMbean(String appsName, String[] targetList, String action){
        
        boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported().booleanValue();
        if (action.equals("enable") || action.equals("true")){
            //when enabling a target, we always ensure that the application is enabled.
                if (getAppStatus(appsName, "domain").equals("false")){
                    MBeanUtil.setAttribute("com.sun.appserv:type=mbean,category=config,name="+appsName, new Attribute("enabled", "true"));
                }
        }
        String status = (action.equals("true") || action.equals("enable")) ? "true" : "false";
        Attribute attr = new Attribute("enabled", status);
        for(int i=0; i<targetList.length; i++){
            String objname = "com.sun.appserv:type=application-ref,category=config,ref="+appsName+",server="+targetList[i];
            MBeanUtil.setAttribute(objname, attr);
        }
    }
    
    
    private void undeploy(CCActionTableModelInterface model, ViewDescriptor vd, String type) {
	RequestContext ctx = RequestManager.getRequestContext();
	String deleteKey = (String)vd.getParameter("deleteKey");
	String objectName = (String)vd.getParameter("rowObjectName");
	//String deleteMethodName = (String)vd.getParameter("deleteMethodName");
	Boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported();
	boolean targetSupported = isTargetSupported == null ? false:isTargetSupported.booleanValue();

	if (deleteKey == null) {
	    throw new FrameworkException("No delete key specified");
	}
	if (objectName == null) {
	    throw new FrameworkException("No ObjectName  specified");
	}

	model.setRowSelectionType("multiple");
        DeploymentFacility df= DeploymentFacilityFactory.getLocalDeploymentFacility();
	try {
	    model.beforeFirst();
	    // from the model, get the child that has the needed value...
	    while(model.next()) {
		if (model.isRowSelected()) {
		    String componentName = model.getValue(deleteKey).toString();
		    if(type.equals("rar")) {
			try {
			    String defaultTarget = ConfigProperties.getInstance().getDefaultTarget();
			    String key = model.getValue(deleteKey).toString();
			    Object[] params = new Object[]{key, defaultTarget};
			    String[] types = new String[]{"java.lang.String", "java.lang.String"};
			    String resourceMethodName = "deleteResourceAdapterConfig";
			    String resourceObjectName = "com.sun.appserv:type=resources,category=config";
			    MBeanUtil.invoke(resourceObjectName, resourceMethodName, params,
					types);
			}
			catch(Exception ex) {
			    //Squelching here is o.k. localize this mesg.
			    Util.logINFO("Deployment Handler deleteResourceAdapter Failed:"+ex.getMessage());
			}
			//commenting this out on 06/10, some reason it doesn't delete rar module.
                        //dProps.setProperty("cascade", "true");
		    }
                    
                    JESProgressObject progressObject = null;
                    String[] targetNames = null;
		    if(targetSupported){
			targetNames = getApplicationTargets(model.getValue(deleteKey).toString(), objectName);
		    }else {
                        targetNames = new String[] {ConfigProperties.getInstance().getDefaultTarget()};
		    }
                    progressObject = df.undeploy(df.createTargets(targetNames), componentName, null);
		    model.setRowSelected(false);
                    DeploymentStatus status = df.waitFor(progressObject);
                    checkDeployStatus(status, null);
		}
	    }
	} catch (Exception ex) {
	    throw new FrameworkException("Error while undeploying: '"+
		vd.getName()+"'", ex, vd, null);
        }
	View view = vd.getView(ctx).getParent();
	ContainerViewBase descView = (ContainerViewBase)view;
	descView.removeChild(vd.getName());
	((DefaultModel)model).clear();
    }
    
    private String[] getApplicationTargets(String name, String objectName) throws Exception {
	ObjectName[] returnValue = null;
	Vector targets = new Vector();
	try {
            returnValue = (ObjectName[])MBeanUtil.invoke(objectName, "listReferencees", new Object[]{name},
				new String[]{"java.lang.String"});
		for(int i = 0; returnValue!=null && i < returnValue.length; i++) {
		    targets.add(MBeanUtil.getAttribute(returnValue[i], "name"));
		}
        } catch (Exception ex) {
	    throw ex;
        }
	if(targets.size() == 0) {
	    String defaultTarget = ConfigProperties.getInstance().getDefaultTarget();
	    targets.add(defaultTarget);
	}
	return (String[])(targets.toArray(new String[targets.size()]));
    }
    
    //Status of app-ref created will be the same as the app itself.
    public void createAppReferences(RequestContext ctx, HandlerContext handlerCtx) {
        String[] targetNames = (String[])handlerCtx.getInputValue("targets");
        if (targetNames != null && targetNames.length > 0){
            String key = (String)handlerCtx.getInputValue("key");
            DeploymentFacility df= DeploymentFacilityFactory.getLocalDeploymentFacility();
            JESProgressObject progressObject = null;
            Properties dProps = new Properties();
            //dProps.setProperty(DeploymentProperties.ENABLE, getAppStatus(key, ConfigProperties.getInstance().getDefaultTarget()));
            progressObject = df.createAppRef(df.createTargets(targetNames), key, dProps);
            DeploymentStatus status = df.waitFor(progressObject);
            checkDeployStatus(status, null);
        }
    }
    
    public void deleteAppReferences(RequestContext ctx, HandlerContext handlerCtx) {
        String[] targetNames = (String[])handlerCtx.getInputValue("targets");
        if (targetNames != null && targetNames.length > 0){
            String key = (String)handlerCtx.getInputValue("key");
            DeploymentFacility df= DeploymentFacilityFactory.getLocalDeploymentFacility();
            JESProgressObject progressObject = null;
            progressObject = df.deleteAppRef(df.createTargets(targetNames), key, null);
            DeploymentStatus status = df.waitFor(progressObject);
            checkDeployStatus(status, null);
        }
    }
    
    /**load
     *	*/
    public void loadDescriptorTableModel(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
	ArrayList displayNamesList = (ArrayList)handlerCtx.getInputValue("displayNames");
	String appName = (String)ctx.getRequest().getAttribute("editKeyValue");
	if (!(handlerCtx.getEvent() instanceof BeforeCreateEvent)) {
	    ViewDescriptor desc = (view instanceof DescriptorContainerView) ?
		((DescriptorContainerView)view).getViewDescriptor() :
		(ViewDescriptor)null;
	    throw new FrameworkException("This handler is for 'beforeCreate'" +
		" handlers only!", desc, view);
	}

        ViewDescriptor desc = ((BeforeCreateEvent)handlerCtx.getEvent()).getViewDescriptor();
        if (!(desc instanceof CCActionTableDescriptor)) {
	    throw new FrameworkException("Table model expected here", desc, view);
        }
        CCActionTableDescriptor ccDesc = (CCActionTableDescriptor)desc;
        CCActionTableModelInterface model = ccDesc.getModel();

        String type = (String)handlerCtx.getInputValue("value");
	if (type == null) {
            throw new FrameworkException("'type' is null in DeploymentHandlers.loadDescriptorTableModel");
	}
	String standardDescriptor = null;
	String sunSpecificDescriptor = null;
	
	String[] descriptors = null;
	if(appName != null) {
	    descriptors = getDescriptors(appName, null);
	    for(int j=0; descriptors != null && j < descriptors.length; j++) {
		model.appendRow();
		model.setValue((String)displayNamesList.get(0), appName);
                int index = descriptors[j].lastIndexOf(File.separator) +1;
		model.setValue((String)displayNamesList.get(1), descriptors[j].substring(index));
		model.setValue("location", descriptors[j]);
	    }
	
	    //load subcomponent descriptors for ear file
	    if(type.equals("j2ee-application")) {
		String[] modules = (String[])MBeanUtil.invoke("com.sun.appserv:type=applications,category=config", "getModuleComponents",
							    new Object[]{appName}, new String[]{"java.lang.String"});
		if(modules != null) {
		    for (int i=0; i < modules.length; i++) {
			try {
			    String subComponentName = new ObjectName(modules[i]).getKeyProperty("name");
			    descriptors = getDescriptors(appName, subComponentName);
			    
			    for(int j=0; descriptors != null && j < descriptors.length; j++) {
				 model.appendRow();
				 model.setValue((String)displayNamesList.get(0), subComponentName);
				 int index = descriptors[j].lastIndexOf(File.separator) +1;
				 model.setValue((String)displayNamesList.get(1), descriptors[j].substring(index));
				 model.setValue("location", descriptors[j]);
			    }
			
			} catch (Exception e){ 
				//we may not reach here.
			    }
		    }
		}
	    }
	}
    }
    
    private String[] getDescriptors(String appName, String subComponent) {
	String[] descriptors = (String[])MBeanUtil.invoke("com.sun.appserv:type=applications,category=config", "getDeploymentDescriptorLocations",
							new Object[]{appName, subComponent}, new String[]{"java.lang.String", "java.lang.String"});
	return descriptors;
    }
    
    static private String getAppStatus(String appName, String target){
        Object status = MBeanUtil.invoke(
                "com.sun.appserv:type=applications,category=config",
                "getStatus",
                new String[] {appName, target},
                new String[] {"java.lang.String", "java.lang.String"}
        );
        return status.toString();
    }
    
    public void getAppStatus2(RequestContext ctx, HandlerContext handlerCtx) {
        handlerCtx.setOutputValue(
            "status", 
            getAppStatus(
                (String)handlerCtx.getInputValue("appName"),
                (String)handlerCtx.getInputValue("target")));
    }
    
     public void loadDeploymentTableModel(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
	if (!(handlerCtx.getEvent() instanceof BeforeCreateEvent)) {
	    ViewDescriptor desc = (view instanceof DescriptorContainerView) ?
		((DescriptorContainerView)view).getViewDescriptor() :
		(ViewDescriptor)null;
	    throw new FrameworkException("This handler is for 'beforeCreate'" +
		" handlers only!", desc, view);
	}

        ViewDescriptor desc = ((BeforeCreateEvent)handlerCtx.getEvent()).getViewDescriptor();
        if (!(desc instanceof CCActionTableDescriptor)) {
	    throw new FrameworkException("Table model expected here", desc, view);
        }
        CCActionTableDescriptor ccDesc = (CCActionTableDescriptor)desc;
        CCActionTableModelInterface model = ccDesc.getModel();
        ((DefaultModel)model).clear();

        ArrayList modelNamesList = (ArrayList)handlerCtx.getInputValue("attributeNames");
        ArrayList displayNamesList = (ArrayList)handlerCtx.getInputValue("displayNames");
        String[] modelNames = (String[])
            modelNamesList.toArray(new String[modelNamesList.size()]);
        Object[] keys = (Object[])handlerCtx.getInputValue("keys");

        if (keys == null) {
            return; //nothing to load..
	}
        for (int rowNo = 0; rowNo < keys.length; rowNo++) {

	    String objectType = null;
	    String type = null;
            ObjectName currentObjName = null;
	    try {
                currentObjName = new ObjectName(keys[rowNo].toString());
		type = currentObjName.getKeyProperty("type");
	    } catch (Exception ex) {
		throw new FrameworkException(ex, ccDesc, view);
	    }
            boolean isApp = false;
            boolean isAppRef = false;
            boolean isResource = false;
            boolean isResourceRef = false;
            if (type != null){
                if (type.equals("application-ref")){
                    isAppRef = true;
                }else
                if (type.equals("resource-ref")){
                    isResourceRef = true;
                }else 
                if (type.equals("j2ee-application") || type.equals("ejb-module") 
                        || type.equals("web-module") || type.equals("connector-module")){
                    isApp = true;
                    objectType = (String)MBeanUtil.getAttribute(currentObjName, "object-type");
                    if( objectType != null && !objectType.equalsIgnoreCase("user")) {
                        continue;
                    }
                }else
                if (type.equals("appclient-module")|| type.equals("lifecycle-module") || type.equals("mbean")){
                    isApp = true;
                }else
                    isResource = true;
            }
            boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported().booleanValue();
            AttributeList attrList = new AttributeList();
            for(int i=0; i < modelNames.length; i++){
                
                String attrValue = (String) MBeanUtil.getAttribute(keys[rowNo].toString(),modelNames[i]);
                if( ! "enabled".equals(modelNames[i])){
                    attrList.add(new Attribute(modelNames[i], attrValue));
                    continue;
                }
                //special handling for the status attribute
                String realStatus = "";
                if (isApp){
                    int statusSummary = getAppStatusSummary( keys[rowNo].toString());
                    realStatus = convertStatusSummary(statusSummary);
                }
                if (isAppRef){
                    String appsName = currentObjName.getKeyProperty("ref");
                    realStatus = getRealTargetStatus(appsName, currentObjName);
                }
                if(isResourceRef){
                    realStatus = getRealResourceTargetStatus(currentObjName);
                }
                if(isResource){
                    int statusSummary = getResourceStatusSummary(currentObjName);
                    realStatus = convertStatusSummary(statusSummary);
                }
                attrList.add(new Attribute(modelNames[i], realStatus));
            }
            model.appendRow();

            for (int i = 0,  colNo = 0; i < attrList.size(); i++) {
                Attribute attr = (Attribute)attrList.get(i);

                while ((colNo <  modelNames.length) && 
                        !attr.getName().equals(modelNames[colNo])) {
                    colNo++;
                }
                if (colNo < modelNames.length) {
                    if (attr.getName().equals("java-web-start-enabled")){
                        String attrValue = ("false".equals(attr.getValue())) ? Util.getMessage("common.Disabled") : Util.getMessage("common.Enabled");
                        model.setValue((String)displayNamesList.get(colNo), attrValue);
                    }else
                        model.setValue((String)displayNamesList.get(colNo), attr.getValue());
                }
            }
            String objn = currentObjName.toString();
            model.setValue("objectName", objn); 
            model.setValue("objectType", type);
        }
    }

    public void loadSubcomponents(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
	ViewDescriptor desc = ((DescriptorCCActionTable)view).getViewDescriptor();
	String moduleName = (String)handlerCtx.getInputValue("moduleName");
        CCActionTableDescriptor ccDesc = (CCActionTableDescriptor)desc;
        CCActionTableModelInterface model = ccDesc.getModel();
	//Make sure to throw error if the attributes are null
	String objectName   = (String)handlerCtx.getInputValue("objectName");
	String methodName = (String)handlerCtx.getInputValue("methodName");
	try {
	    String[] modules = (String[])MBeanUtil.invoke(objectName, methodName,
							new Object[]{moduleName}, new String[]{"java.lang.String"});
		for(int i = 0; i < modules.length; i++) {
		    ObjectName on = new ObjectName(modules[i]);
		    model.appendRow();
		    //Get the display field names from XML file
		    model.setValue("componentName", on.getKeyProperty("name"));
		    model.setValue("componentType", on.getKeyProperty("j2eeType"));
		}
	} catch (Exception ex) {
	    throw new FrameworkException(
		"Exception thrown while attempting to get Modules List.",
		ex, ccDesc, view);
	}
    }
    //Method display the field from the propertysheet if Target is supported. We may move this to 
    //TargetHandlers if necessary, i.e. if used in many places.
    public void displayDeployPageChild(RequestContext ctx, HandlerContext handlerCtx) throws Exception {
	View view = handlerCtx.getView();
	if (!(view instanceof DescriptorContainerView)) {
            View parent = view.getParent();
            if (!(parent instanceof DescriptorContainerView)) {
		throw new FrameworkException("View is not a DescriptorContainerView!", null, view);
            }  else {
                view = parent;
            }
        }
        if (view instanceof DescriptorCCPageTitle) {
            view = view.getParent();
        }
	DescriptorContainerView descView = (DescriptorContainerView)view;
	Boolean isTargetSupported = 
            ConfigProperties.getInstance().getTargetSupported();
        String propertyName = (String)handlerCtx.getInputValue("propertyName");
        ViewDescriptor propertySheetDescriptor = descView.getViewDescriptor();
	
	if (propertyName == null) {
	    throw new FrameworkException("displayVirtualserver: propertySheetName is null", propertySheetDescriptor, view);
	}
	
	if (propertySheetDescriptor == null) {
	    throw new FrameworkException("displaVirtualServer: propertySheetDescriptor is null", propertySheetDescriptor, view);
	}
	if(!(propertySheetDescriptor instanceof CCPropertySheetDescriptor)) {
	    throw new FrameworkException("displayVirtualServer: propertySheetDescriptor is of wrong type", propertySheetDescriptor, view);
	}
        CCPropertySheetModelInterface model = ((CCPropertySheetDescriptor)propertySheetDescriptor).getModel();
	
	if (isTargetSupported != null && isTargetSupported.booleanValue()) {
	    model.setVisible(propertyName, false);
            handlerCtx.setOutputValue("value", "true");
	} else {
	    model.setVisible(propertyName, true);
            handlerCtx.setOutputValue("value", "false");
        }
    }
    
    public String endExecuteLinkDisplay(RequestContext ctx, HandlerContext handlerCtx) {
	View bean = handlerCtx.getView();
        ChildContentDisplayEvent ev = (ChildContentDisplayEvent)handlerCtx.getEvent();
        String content = ev.getContent();
        String isWebService = (String)handlerCtx.getInputValue("isWebService");
        String appName = (String)handlerCtx.getInputValue("appName");
        String port = null;
        try {
            port = getPortForApplication(appName);
        } catch (Exception ex) {
            ex.printStackTrace(); // ignore this exception..
        }

        String serverName =  ctx.getRequest().getServerName();
        String ctxtRoot= (String)handlerCtx.getInputValue("ctxtRoot");
        if (ctxtRoot == null || ctxtRoot.length() == 0) {
            ctxtRoot = "/";
	}
        if (ctxtRoot.indexOf("/") != 0) {
            ctxtRoot = "/" + ctxtRoot;
	}
        String text = removeProp(content, "onclick");
        if (port != null) {
            if (isWebService == null) {
                content = addProp(removeProp(text, "href"), 
                    "href=\"http://" + serverName + ":" + port + ctxtRoot + "\" target=\"_blank\"");
            } else {
                content = addProp(text, 
                    "onClick=\"window.open('http://" + serverName + ":" + port + ctxtRoot + "');document.Form.target='_self'\"");   //Web Service Tester form
            }
        }
        else {
            if (isWebService == null) {
                content = addProp(removeProp(text, "href"), 
                    "href=\""+ ctxtRoot +"\" target=\"_blank\"");
            } else {
                content = addProp(text, 
                    "onClick=\"window.open('"+ ctxtRoot + "');document.Form.target='_self'\"");  //Web Service Tester form
            }
        }
        return content;
    }
    
    
     public void getLaunchURLPath(RequestContext ctx, HandlerContext handlerCtx) {
	View bean = handlerCtx.getView();
        String appclientName = (String)handlerCtx.getInputValue("appclientName");
        String applicationName = (String)handlerCtx.getInputValue("applicationName");
        if (Util.isEmpty(appclientName))
            throw new FrameworkException("Deployment.getLaunchURLPath(), appclientName is NULL");
        try {
            String jwsEnabled ;
            if (Util.isEmpty(applicationName))
                jwsEnabled = (String) MBeanUtil.getAttribute("com.sun.appserv:type=appclient-module,category=config,name="+appclientName, "java-web-start-enabled");
            else
                jwsEnabled = (String) MBeanUtil.getAttribute("com.sun.appserv:type=j2ee-application,category=config,name="+applicationName, "java-web-start-enabled");
            if ( "false".equals(jwsEnabled)){
                handlerCtx.setOutputValue("isEnabled", Boolean.FALSE);
                return;
            }
                
            NamingConventions nc = new NamingConventions();
            String path = (Util.isEmpty(applicationName)) ? nc.getLaunchURLPath(appclientName) :
                           nc.getLaunchURLPath(applicationName, appclientName); 
            if (!Util.isEmpty(path)){
                handlerCtx.setOutputValue("path", path);
                handlerCtx.setOutputValue("isEnabled", Boolean.TRUE);
            }else
                handlerCtx.setOutputValue("isEnabled", Boolean.FALSE);
            
        }catch (Exception ex){
            //NamingConvention may throw ConfigException. log it and assume null.
            Util.logFINE(ex);
            ex.printStackTrace();
            handlerCtx.setOutputValue("isEnabled", Boolean.FALSE);
        }
     }
     
      public void getAppClientLinkPE(RequestContext ctx, HandlerContext handlerCtx) {
            String appName = (String)handlerCtx.getInputValue("appId");
            String port = null;
            try {
                port = getPortForApplication(appName);
            } catch (Exception ex) {
                ex.printStackTrace(); // ignore this exception..
            }
            String serverName =  ctx.getRequest().getServerName();
            String appendUrl = (String)handlerCtx.getInputValue("appendUrl");
            if (port != null) 
                appendUrl = "http://" + serverName + ":"  + port  + appendUrl;
            handlerCtx.setOutputValue("appClientLink", appendUrl);
      }
      
     
     public void getAppClientLinks(RequestContext ctx, HandlerContext handlerCtx) {
	// First get the application id
	String id = (String)handlerCtx.getInputValue("appId");
        String appendUrl = (String)handlerCtx.getInputValue("appendUrl");
        if (appendUrl != null) {
            appendUrl = ((appendUrl.startsWith("/") ? appendUrl.substring(1) : appendUrl));
        }
	// Get all the URLs
	List urls = getURLs(id, getWebAppReferencees(id));
        String[] values = new String[urls.size()];
        for(int i=0; i< urls.size(); i++){
            values[i] = (String) urls.get(i)+appendUrl;
        }
        handlerCtx.setOutputValue("appClientLinks", values);
     }
     
     
     // Framework callback method to dynamically fill in choices of a dropdown menu. 
    public void populateRadioButtons(RequestContext ctx, HandlerContext handlerCtx) {
        // the child should be something like: com.sun.web.ui.view.html.CCDropDownMenu
        SelectableGroup radioButtonChild = (SelectableGroup) handlerCtx.getView();
        // get the parent container of the dropdown
        DescriptorContainerView parent = (DescriptorContainerView) radioButtonChild.getParent();
        
        // need the child descriptor to get a parameter, retrieve from the parent descriptor.
        ViewDescriptor vd = parent.getViewDescriptor();
        ViewDescriptor cvd = vd.getChildDescriptor(radioButtonChild.getName());
        
        String[] appClientLinks = (String[]) handlerCtx.getInputValue("appClientLinks");
        OptionList options = new OptionList( appClientLinks, appClientLinks); // label and values
        radioButtonChild.setOptions(options);
        radioButtonChild.setValue(appClientLinks[0]);
    }

    // returns 'first' nonadmin virtual server -
    private String getNonAdminVirtualServer() {
        String vsId = null;
        ObjectName[] vsObjectNames = (ObjectName[])
            MBeanUtil.invoke("ias:type=configs,category=config",
            "listVirtualServers",
            new Object[]{null},
            new String[]{"java.lang.String"});
        if (vsObjectNames != null) {
            for (int i = 0; i < vsObjectNames.length; i++) {
                String id = (String)MBeanUtil.getAttribute(vsObjectNames[i], "id");
                if (!(id.equals("__asadmin"))) {
                    vsId = id;
                    break;
                }
            }
        }
        return vsId;
    }

    /* returns the port number on which appName could be executed */
    private String getPortForApplication(String appName) {
        ObjectName appRef = (ObjectName)MBeanUtil.invoke
            ("ias:type=server,name=server,category=config",
            "getApplicationRefByRef",
            new Object[]{appName},
            new String[]{"java.lang.String"});

        String vsId = null;
        if (appRef == null) { // no ref found for this application
            vsId = getNonAdminVirtualServer();
        }
        else {
            vsId = (String)MBeanUtil.getAttribute(appRef, "virtual-servers");
            if (vsId == null || vsId.length() ==0) { // no vs found for this application
                vsId = getNonAdminVirtualServer();
            } else {
                if (vsId.indexOf(",") > 0) {
                    vsId = vsId.substring(0, vsId.indexOf(","));
                }
            }
        }
        if (vsId == null)
            return null; // no vs found for this app..

        String port = null;
        ObjectName vsObjectName = (ObjectName)
            MBeanUtil.invoke("ias:type=configs,category=config",
            "getVirtualServer",
            new Object[]{vsId, null},
            new String[]{"java.lang.String", "java.lang.String"});
        if (vsObjectName != null) {
            String listener = (String)MBeanUtil.getAttribute(vsObjectName, "http-listeners");
            if (listener != null) {
                if (listener.indexOf(",") > 0) {
                    listener = listener.substring(0, listener.indexOf(","));
                }
                ObjectName listenerObjectName = (ObjectName)
                    MBeanUtil.invoke("ias:type=configs,category=config",
                    "getHttpListener",
                    new Object[]{listener, null},
                    new String[]{"java.lang.String", "java.lang.String"});
                port = (String)MBeanUtil.getAttribute(listenerObjectName, "port");
            }
        }
        return port;
    }
 

    private String addProp(String tag, String addText) {
        int i = tag.indexOf(' ');
        if (i<0) {
            return tag;
	}
        String text = tag.substring(0,i) + " " + addText + tag.substring(i,tag.length());
        return text;
    }

    private String removeProp(String tag, String prop) {
        int i = tag.indexOf(prop);
        if (i<0) return tag;
        int j = tag.indexOf('\"', i+2+prop.length());
        if (j<0) return tag;
        String text = "";
        if(prop.equals("onclick")) {
            text = tag.substring(0,i) + tag.substring(j+1, tag.length());
        } else {
            text = tag.substring(0,i) + tag.substring(j+2, tag.length());
        }
        return text;
    }


    /**
     *	This method is used as a fallback when no Hostname is provided.
     */
    public static String getDefaultHostName() {
        String defaultHostName = "localhost";
	try {
	    InetAddress host = InetAddress.getLocalHost();
	    defaultHostName = host.getCanonicalHostName();
	} catch(UnknownHostException uhe) {
//	    sLogger.log(Level.FINEST, "mbean.get_local_host_error", uhe);
//	    sLogger.log(Level.INFO, "mbean.use_default_host");
	}
	return defaultHostName;
    }


    /**
     *	This method determines the hostname of the given serverInstance
     *	ObjectName to the best of its ability.  It will attempt to obtain the node-agent....
     *
     *	@param	serverInstance	The ObjectName to use to determine the hostname
     */
    protected String getHost(ObjectName serverInstance) {
	// Find the node agent (if there is one)
	String nodeAgentRef = (String)MBeanUtil.getAttribute(serverInstance, "node-agent-ref");
	if ((nodeAgentRef == null) || nodeAgentRef.equals("")) {
	    return getDefaultHostName();
	}

	// Get the JMX connector for the node agent
	ObjectName jmxConnector = (ObjectName)MBeanUtil.invoke(
		"com.sun.appserv:type=node-agent,name="+nodeAgentRef+
		    ",category=config",
		"getJmxConnector", null, null);
	if (jmxConnector == null) {
	    return getDefaultHostName();
	}
	
	// Try to get the hostname
	// Get "client-hostname" from the properties (use this way instead
	// of getProperty to avoid exception
	AttributeList properties = (AttributeList)MBeanUtil.invoke(
		jmxConnector, "getProperties", null, null);
	Attribute att;
	String hostName = null;
	Iterator it = properties.iterator();
	while (it.hasNext()) {
	    att = (Attribute)it.next();
	    if (att.getName().equals("client-hostname")) {
		hostName = (String)att.getValue();
		break;
	    }
	}

	// Get default host name
	if ((hostName == null) || hostName.equals("") || hostName.equals("0.0.0.0")) {
	    return getDefaultHostName();
	}

	// We found the hostname!!
	return hostName;
    }


    /**
     *
     *	@param	src		The String which may contain tokens for
     *				substitution.
     *
     *	@param	serverInstance	The serverInstance which has the system
     *				properties.
     */
    protected String replaceTokens(ObjectName serverInstance, String src) {
	int idx = src.lastIndexOf("${");
	if (idx < 0) {
	    // Nothing to do
	    return src;
	}

	// Get the Properties
	Properties sysProp = (Properties)
	    MBeanUtil.invoke(serverInstance, "listSystemProperties",
		new Object[]{ new Boolean("true")}, new String[]{"boolean"});
	int endIdx;
	String newString;
	while (idx > -1) {
	    endIdx = src.indexOf("}", idx+2);
	    newString =
		src.substring(0, idx)+
		sysProp.getProperty(src.substring(idx+2, endIdx)) +
		src.substring(endIdx+1);
	    src = newString;
	    idx = src.lastIndexOf("${");
	}

	// Return the result after the substitution(s)
	return src;
    }


    /**
     *	This method expects a ObjectName to a server instance (not a cluster).
     *	It will obtain its configuration and determine its concrete port
     *	number(s).
     */
    protected List getURLs(String appId, ObjectName serverInstance) {
	// Get the config ref name, this is used in a couple places below
	String configRef = (String)MBeanUtil.getAttribute(serverInstance, "config-ref");

	// First get the application-ref ObjectName
	String name = (String)MBeanUtil.getAttribute(serverInstance, "name");
	String appObj = "com.sun.appserv:type=application-ref,ref="+appId+",server="+name+",category=config";

	// Next get the virtual server(s)
	String strVirServers = (String)MBeanUtil.getAttribute(appObj, "virtual-servers");
	if ((strVirServers == null) || strVirServers.equals("")) {
	    // No virtual server was specified, we must look at the listeners,
	    // find the first *enabled* listener, then look at the listener's
	    // *default* virtual server's listeners (backwards I know... but
	    // this is how it is).

	    // First get all the listeners for this instance
	    ObjectName listeners[] = (ObjectName[])MBeanUtil.invoke(
		"com.sun.appserv:type=http-service,config="+configRef+
		",category=config", "getHttpListener", null, null);

	    // Find the first enabled listener
	    int count=0;
	    while (count<listeners.length) {
		if (((String)MBeanUtil.getAttribute(listeners[count],
		    "enabled")).equals("true")) {
		    break;
		}
		count++;
	    }
	    if (count == listeners.length) {
		// There are no enabled listeners, return an empty List
		return new ArrayList(0);
	    }

	    // Now pull off the default-virutal-server
	    strVirServers = (String)MBeanUtil.getAttribute(listeners[count],
		"default-virtual-server");
	}

	// Next get the http listeners from the virtual servers
	String virServer;
	String listeners;
	Iterator listIt;
	String listener;
	List listenerList = new ArrayList();
	Iterator it = Util.parseStringList(strVirServers, " ,").iterator();
	while (it.hasNext()) {
	    // Get each virtual server's list of listeners
	    virServer = (String)it.next();
	    listeners = (String)MBeanUtil.getAttribute(
		"com.sun.appserv:type=virtual-server,id="+virServer+
		    ",config="+configRef+",category=config",
		"http-listeners");
	    listIt = Util.parseStringList(listeners, " ,").iterator();

	    // Add each unique listener
	    while (listIt.hasNext()) {
		listener = (String)listIt.next();
		if (!listenerList.contains(listener)) {
		    // Only add unique listeners
		    listenerList.add(listener);
		}
	    }
	}

	// There will be 1 URL per listener
	List urls = new ArrayList(listenerList.size());
	StringBuffer url = null;
	String listenerObj;
	it = listenerList.iterator();
	while (it.hasNext()) {
	    // Get the next listener
	    listenerObj = "com.sun.appserv:type=http-listener,id="+it.next()
		+",config="+configRef+",category=config";

	    // Start the URL
	    url = new StringBuffer("http");
	    if (MBeanUtil.getAttribute(listenerObj, "security-enabled").toString().equals("true")) {
		// Security is enabled on this port, add an 's'
		url.append("s");
	    }
	    url.append("://");

	    // Host
	    url.append(getHost(serverInstance));
	    url.append(":");

	    // Port
	    url.append(replaceTokens(serverInstance, (String)MBeanUtil.getAttribute(listenerObj, "port")));
	    url.append("/");

	    // Add the URL to the List
	    urls.add(url.toString());
	}

	return urls;
    }


    /**
     *	This method takes an array of object name.  These object names may
     *	either be server instances or cluster instances.  It will get the
     *	cluster's instances and recurse.  It will pass the server instances to
     *	getURLs(ObjectName).
     *
     *	@param	serverInstance	An array of ObjectName, server instances
     *				and/or clusters
     */
    protected List getURLs(String appId, ObjectName serverInstances[]) {
	// Iterate over all the supplied server instance ObjectNames
	List urls = new ArrayList();
	for (int count=0; count<serverInstances.length; count++) {
	    if (serverInstances[count].getKeyProperty("type").equals("cluster")) {
		// We found a cluster, get the server instances in the cluster
		// listServerInstances returns: com.sun.appserv:type=server,name=Instance1A,category=config
		urls.addAll(getURLs(appId, (ObjectName[])MBeanUtil.invoke(
		    serverInstances[count],
		    "listServerInstances", null, null)));
	    } else {
		// We have a Server Instance, just get the urls
		urls.addAll(getURLs(appId, serverInstances[count]));
	    }
	}

	// Return the URLs
	return urls;
    }


    /**
     *	This method finds all the webapps associated w/ appId
     *
     *	@param	appId	The application
     *
     *	@return	The ObjectName[] of servers / clusters
     */
    protected ObjectName[] getWebAppReferencees(String appId) {
	return (ObjectName[])MBeanUtil.invoke(
	    "com.sun.appserv:type=applications,category=config",
	    "listReferencees",
	    new Object[] { appId },
	    new String[] { "java.lang.String" });
    }


    /**
     *	This method uses the given appId to find all the possible
     *	server/port combinations available for accessing the application.  It
     *	will create String representing the concatenation of all the URLs
     *	seperated by <BR>'s.
     */
    public String getWebAppHrefs(RequestContext ctx, HandlerContext handlerCtx) {
	// First get the application id
	String id = (String)handlerCtx.getInputValue("appId");
        String appendUrl = (String)handlerCtx.getInputValue("appendUrl");

        if (appendUrl != null) {
            appendUrl = ((appendUrl.startsWith("/") ? appendUrl.substring(1) : appendUrl));
        }
        
	// getWebAppReferencees = com.sun.appserv:type=cluster,name=Cluster1,category=config
	// getWebAppReferencees = com.sun.appserv:type=server,name=server,category=config

	// Get all the URLs
	List urls = getURLs(id, getWebAppReferencees(id));

	// Check to see if we have a Model to populate...
	DefaultModel model = (DefaultModel)handlerCtx.getInputValue("model");
	if (model != null) {
	    // Initialize the model...
	    model.clear();
	}

	// Create a default output, plus popluate the supplied Model (if any)
	StringBuffer output = new StringBuffer("");
	Iterator it = urls.iterator();
	String url = null;
	while (it.hasNext()) {
	    url = (String)it.next();       
            url = url + appendUrl;
            
	    // Add each URL to the output string
	    output.append("<A href=\""+url+"\" target=\"_blank\">"+url+"</A><BR>");

	    // Add each URL to the Model
	    model.appendRow();
	    model.setValue("link", url);
	}

	// Return a String containing all the URLs
	return output.toString();
    }

    public void getApplicationStatusSummary(RequestContext ctx, HandlerContext handlerCtx) {
	// First get the application id
	String appsName = (String)handlerCtx.getInputValue("appsName");
        int status = getAppStatusSummary(appsName);
        String result = convertStatusSummary(status);
        if (result == null) {
            //error case, will only occur for PE.
            result = "false" ;
            Util.logWARNING("======= Error in getting enabled status for '" + appsName + "'" );
        }
        handlerCtx.setOutputValue("value", result);
    }
    
    public void getResourceStatusSummary(RequestContext ctx, HandlerContext handlerCtx) {
	String resObj = (String)handlerCtx.getInputValue("resObjectName");
        try{
            int status = getResourceStatusSummary(new ObjectName(resObj));
            String result = convertStatusSummary(status);
            handlerCtx.setOutputValue("value", result);
        }catch (Exception ex){
            throw new FrameworkException("error in getResourceStatusSummary ", ex);
        }
    }
    
    public void getRealTargetStatus(RequestContext ctx, HandlerContext handlerCtx) {
	// First get the application id
	String appsName = (String)handlerCtx.getInputValue("appsName");
        String target = (String)handlerCtx.getInputValue("target");
        String status = getRealTargetStatus(appsName, target);
        handlerCtx.setOutputValue("value", status);
    }
    
    private String getRealTargetStatus(String appsName, Object target){
        try{
            String enabled = getAppStatus(appsName, "domain");
            if ("false".equals(enabled)){
                return "false";
            }else{
                if(target instanceof ObjectName)
                    return (String) MBeanUtil.getAttribute((ObjectName)target, "enabled");
                else
                    return getAppStatus(appsName, (String)target);
            }
        }catch(Exception ex){
            //for the case of app client, it will failed. we just catch it here.
            return "";
        }
    }
    
    public void getRealResourceTargetStatus(RequestContext ctx, HandlerContext handlerCtx) {
	// First get the application id
        try {
            String refsObjectName = (String)handlerCtx.getInputValue("refsObjectName");
            ObjectName refsObject = new ObjectName(refsObjectName);
            String status = getRealResourceTargetStatus(refsObject);
            handlerCtx.setOutputValue("value", status);
        }catch(Exception ex){
            throw new FrameworkException("Error in getRealResourceTargetStatus ", ex);
        }
    }
   
    public void saveStatusPE(RequestContext ctx, HandlerContext handlerCtx) {
        try {
            ObjectName objectName = new ObjectName((String)handlerCtx.getInputValue("objectName"));
            ObjectName refObjectName = new ObjectName((String)handlerCtx.getInputValue("refObjectName"));
            String value = (String)handlerCtx.getInputValue("value");
            
            //type will either be application-ref or resource-ref
            //for applications, need to go through deployment facility to enable/disable.
            
            if(refObjectName.getKeyProperty("type").equals("application-ref") && 
                !(objectName.getKeyProperty("type").equals("mbean"))){
                changeEnableStatus(objectName.getKeyProperty("name"), new String[] { "server" }, value);
            }else{
                MBeanUtil.setAttribute(objectName, new Attribute("enabled", "true"));
                MBeanUtil.setAttribute(refObjectName, new Attribute("enabled", value));
            }
        }catch(Exception ex){
            throw new FrameworkException(ex);
        }
    }
    
    private String getRealResourceTargetStatus(ObjectName refsObject){
        String resName = refsObject.getKeyProperty("ref");
        String resType = (String) MBeanUtil.invoke(
                "com.sun.com.sun.appserv:type=resources,category=config",
                "getResourceType",
                new String[] {resName},
                new String[] {"java.lang.String"}); 
        try{
            ObjectName obj = new ObjectName("com.sun.appserv:category=config,type="+resType+",jndi-name="+resName);
            String status = (String) MBeanUtil.getAttribute(obj, "enabled");
            if ("true".equals(status)){
                status = (String) MBeanUtil.getAttribute(refsObject, "enabled");
            }
            return status;
        }catch(Exception ex){
            throw new FrameworkException("Error in getRealResourceTargetStatus", ex);
        }
    }
    
   /* return -2: no target associated. 
    *       -1 : all targets enabled
    *        0 : all targets disabled
    *  otherwise, the # of targets thats enabled.
    */
   private int getAppStatusSummary(String appsObjName)
   {
       ObjectName[]refs = null;
       int count =0;
       try{
           String appsName=(String) MBeanUtil.getAttribute(appsObjName, "name");
           boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported().booleanValue();
           if (!isTargetSupported){
                ObjectName server = new ObjectName("com.sun.appserv:type=server,name=server,category=config");
                refs = new ObjectName[]{server};
           }else{
               String[] params = new String[] {appsName};
               String[] types = new String[] {"java.lang.String"};
               refs = (ObjectName[]) MBeanUtil.invoke("com.sun.appserv:type=applications,category=config" , "listReferencees", params, types);
               if (refs.length ==0) 
                   return APP_NO_TARGET;
           }
           String status = getAppStatus(appsName, ConfigProperties.getInstance().getDefaultTarget());
           if ("false".equals(status))
               return APP_ALL_DISABLED;
           for(int i=0; i < refs.length; i++){
               String[] params = new String[] {appsName};
               String[] types = new String[] {"java.lang.String"};
               ObjectName appRefsObj = (ObjectName)MBeanUtil.invoke( refs[i], "getApplicationRefByRef",  params, types );
               String refStatus = (String)MBeanUtil.getAttribute(appRefsObj, "enabled");
               if ("true".equals(refStatus)){
                   count++;
               }
           }
           if (count == refs.length) return APP_ALL_ENABLED;
           return count;
        }catch(Exception ex){
           Util.logSEVERE(ex);
           return APP_UNKNOWN;
       }
    }
   
   /* return -2: no target associated. 
    *       -1 : all targets enabled
    *        0 : all targets disabled
    *  otherwise, the # of targets thats enabled.
    */
   private int getResourceStatusSummary(ObjectName resObject)
   {
       String resName = resObject.getKeyProperty("jndi-name");
       int count = 0;
       String[] params = new String[] {resName};
       String[] types = new String[] {"java.lang.String"};
       ObjectName[] refs = null;
       boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported().booleanValue();
       try {
            if (!isTargetSupported){
                   ObjectName server = new ObjectName("com.sun.appserv:type=server,name=server,category=config");
                   refs = new ObjectName[]{server};
           }else{
                refs = (ObjectName[]) MBeanUtil.invoke("com.sun.appserv:type=resources,category=config" , "listReferencees", params, types);
                if (refs.length ==0) 
                    return APP_NO_TARGET;
           }
           String status = (String)MBeanUtil.getAttribute(resObject, "enabled");
           if ("false".equals(status))
               return APP_ALL_DISABLED;
           for(int i=0; i < refs.length; i++){
               ObjectName resRefsObj = (ObjectName)MBeanUtil.invoke( refs[i], "getResourceRefByRef",  params, types );
               String refStatus = (String)MBeanUtil.getAttribute(resRefsObj, "enabled");
               if ("true".equals(refStatus)){
                   count++;
               }
           }
           if (count == refs.length) return APP_ALL_ENABLED;
           return count;
       }catch(Exception ex){
           Util.logWARNING(ex);
           return APP_UNKNOWN;
       }
    }
   
     private String convertStatusSummary(int statusSummary){
        String disp = null;
        boolean isTargetSupported = ConfigProperties.getInstance().getTargetSupported().booleanValue();
        if (statusSummary == APP_UNKNOWN){
            disp = (isTargetSupported)?Util.getMessage("deploy.unknown") : "false" ; //PE is checkbox that require true or false.
        }else
        if (statusSummary == APP_ALL_ENABLED){
            disp = (isTargetSupported)?Util.getMessage("deploy.allEnabled") : "true";
        }else
        if (statusSummary == APP_ALL_DISABLED){
            disp = (isTargetSupported)?Util.getMessage("deploy.allDisabled") : "false";
        }else
        if (statusSummary == APP_NO_TARGET){
            disp = (isTargetSupported)? Util.getMessage("deploy.noTarget") : "true";
        }else{
            //should not get here for PE
            disp = (isTargetSupported)? Util.getMessage("deploy.someEnabled", new String[]{""+statusSummary}) : "true";
        }
        return disp;
                    
     }
     
    public void loadMbeanAttrTable(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
        ViewDescriptor desc = null;
        if (handlerCtx.getEvent() instanceof BeforeCreateEvent) {
            desc = ((BeforeCreateEvent)handlerCtx.getEvent()).getViewDescriptor();
	} else {
            DescriptorContainerView descView = (DescriptorContainerView)
                (((ViewBase)view).getParentViewBean());
            desc = descView.getViewDescriptor();
        }
        CCActionTableModelInterface model =(CCActionTableModelInterface)handlerCtx.getInputValue("model");
        if (model == null) {
            throw new FrameworkException("loadCallFlowDataTable: No Model Specified.",
                desc, handlerCtx.getView());
        }
        String implClass = (String)handlerCtx.getInputValue("implClass");
        Boolean create = (Boolean)handlerCtx.getInputValue("create");
	
        Object[] params = {implClass};
        String[] types = {"java.lang.String"};
        MBeanInfo mbinfo = (MBeanInfo) MBeanUtil.invoke("com.sun.appserv:type=applications,category=config", "getMBeanInfo", params, types);
        MBeanAttributeInfo[] attrArray = mbinfo.getAttributes();
        if (attrArray == null || attrArray.length < 0){
            return;
        }
        AttributeList attrList = null;
        if(!create){
            String objName = (String)handlerCtx.getInputValue("mbeanObjectName");
            attrList = (AttributeList) MBeanUtil.invoke(objName, "getProperties", null, null);
        }
        
        ((DefaultModel)model).clear();
        try {
            model.beforeFirst();
            for(int i=0; i<attrArray.length; i++){
                model.appendRow();
                String name = attrArray[i].getName();
                model.setValue("propertyName", name);
                model.setValue("type", attrArray[i].getType());
                if(!create){
                    String val = getMbeanPropertyValue(attrList, name);
                    if (val != null)
                        model.setValue("propertyValue", val);
                }
            }
//            System.out.println("beginDisplay: After Loading Table =============== ");
//            ((DefaultModel)model).dumpValues(System.out);
            
        }catch (Exception ex) {
            throw new FrameworkException(ex);
        }
    }
    
    private String getMbeanPropertyValue(AttributeList attrList, String name){
        if( attrList == null) 
            return null;
        Iterator it = attrList.iterator();
        while (it.hasNext()) {
            Attribute att = (Attribute)it.next();
            if (att.getName().equals(name)) {
                return  (String) att.getValue();
            }
        }
        return null;
    }
    
    public void getMbeanAttrFromTable(RequestContext ctx, HandlerContext handlerCtx) throws ModelControlException {
	Boolean ignoreEmptyValues = (Boolean)handlerCtx.getInputValue("ignoreEmptyValues");
        CCActionTableModelInterface model = (CCActionTableModelInterface)handlerCtx.getInputValue("propertiesModel");
//        System.out.println("=== Just before getting Value from Table");
//        ((DefaultModel)model).dumpValues(System.out);
        model.beforeFirst();
        Properties properties = new Properties();
        while (model.next()) {
            String name = (String) model.getValue("propertyName");
            String value = (String) model.getValue("propertyValue");
            if (!Util.isEmpty(name)) {
                if (Util.isEmpty(value)) {
                    if (ignoreEmptyValues!=null && ignoreEmptyValues.booleanValue()==true)
                        continue;
                }
                properties.setProperty(name, value);
            }
        }
        handlerCtx.setOutputValue("properties", properties);
    }
    
     
    //Deployment constants
    public static final String FORCE		= "force";
    public static final String DEFAULT_FORCE	= "true";
    public static final String CASCADE		= "cascade";
    public static final String DEFAULT_CASCADE  = "false";
    public static final String VERIFY		= "verify";
    public static final String DEFAULT_VERIFY	= "false";
    public static final String PRECOMPILE_JSP	= "precompilejsp";
    public static final String ENABLE		= "enable";
    public static final String CONTEXT_ROOT	= "contextRoot";
    public static final String ARCHIVE_NAME	= "archiveName";
    public static final String NAME		= "name";
    public static final String TYPE		= "type";
    public static final String TARGET		= "target";

    //DisplayField constants
    public static final String LOCATION		= "location";
    public static final String REDEPLOY		= "redeploy";
    
    public static final String	PROPERTY_NAME	= "propertyName";
    public static final String	PROPERTY_VALUE 	= "propertyValue";
    
    public static final int APP_UNKNOWN = -3;
    public static final int APP_NO_TARGET = -2;
    public static final int APP_ALL_ENABLED = -1;
    public static final int APP_ALL_DISABLED = 0;
    
    
    
    
}
