All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sun.jbi.management.system.DeploymentService Maven / Gradle / Ivy

Go to download

JBI Runtime Management components, providing installation, deployment, and other JMX interfaces for remote management consoles.

There is a newer version: 2.4.3
Show newest version
/*
 * BEGIN_HEADER - DO NOT EDIT
 *
 * 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://open-esb.dev.java.net/public/CDDLv1.0.html.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * HEADER in each file and include the License file at
 * https://open-esb.dev.java.net/public/CDDLv1.0.html.
 * If applicable add the following below this CDDL HEADER,
 * with the fields enclosed by brackets "[]" replaced with
 * your own identifying information: Portions Copyright
 * [year] [name of copyright owner]
 */

/*
 * @(#)DeploymentService.java
 * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
 *
 * END_HEADER - DO NOT EDIT
 */
package com.sun.jbi.management.system;


import com.sun.jbi.ComponentInfo;
import com.sun.jbi.ComponentState;
import com.sun.jbi.ComponentType;
import com.sun.jbi.ServiceAssemblyInfo;
import com.sun.jbi.ServiceAssemblyQuery;
import com.sun.jbi.ServiceAssemblyState;
import com.sun.jbi.ServiceUnitInfo;
import com.sun.jbi.ServiceUnitState;
import com.sun.jbi.ServiceUnitRegistration;
import com.sun.jbi.StringTranslator;
import com.sun.jbi.framework.DeployerMBean;
import com.sun.jbi.framework.EventNotifierCommon;
import com.sun.jbi.management.ComponentMessageHolder;
import com.sun.jbi.management.LocalStringKeys;
import com.sun.jbi.management.MBeanNames;
import com.sun.jbi.management.internal.support.DirectoryUtil;
import com.sun.jbi.management.internal.support.DOMUtil;
import com.sun.jbi.management.message.MessageBuilder;
import com.sun.jbi.management.message.MessageHelper;
import com.sun.jbi.management.descriptor.ServiceAssemblyDescriptor;
import com.sun.jbi.management.registry.data.ServiceAssemblyInfoImpl;
import com.sun.jbi.management.repository.Archive;
import com.sun.jbi.management.repository.ArchiveType;
import com.sun.jbi.management.support.JbiNameInfo;
import com.sun.jbi.management.util.FileHelper;
import com.sun.jbi.messaging.Link;
import com.sun.jbi.messaging.ConnectionManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.Enumeration;

import javax.jbi.JBIException;
import javax.jbi.management.DeploymentServiceMBean;
import javax.jbi.management.DeploymentException;

import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * This is the Deployment Service, which is responsible for the management
 * and administration of Service Assemblies.
 *
 * @author Sun Microsystems, Inc.
 */
public class DeploymentService extends ModelSystemService
    implements com.sun.jbi.management.DeploymentServiceMBean
{
    /**
     * Management context
     */
    private static ManagementContext sMContext = null;
    
    
    /**
     * Management Message Impl
     */
    private BuildManagementMessageImpl mMImpl = null;
    
    /*
     *   JBI deploy root
     */
    private String dplyRoot = null;
    
    /**
     * file that gets created when a directory is not successfully deleted
     */
    private static final String PATH_TO_DELETE_ME_FILE = ".DELETE_ME";
    
    /**
     * Handle to StringTranslator for message translation
     */
    private StringTranslator mTranslator;
    
    private final JbiNameInfo mJbiNameInfo = new JbiNameInfo("DeploymentService");
    
    /**
     * statistics mbean
     */
    private DeploymentServiceStatisticsMBean mStatisticsMBean;
    
    /**
     * map of SA names to SA stats objects
     */
    private Map
            mServiceAssemblyStats = new HashMap();
    
    /**
     * statistics enable/disable flag
     */
    private boolean mStatisticsEnabled = true;
    
    /** lifecycle operation start */
    private static String START = "start";
    
    /** lifecycle operation stop */
    private static String STOP = "stop";

    /** lifecycle operation shut down */
    private static String SHUTDOWN = "shutDown";

    /** Constructs a DeploymentService.
     * @param anEnv ManagementContext.
     */
    public DeploymentService(ManagementContext anEnv)
    throws JBIException
    {
        sMContext = anEnv;
        mMImpl = new BuildManagementMessageImpl();
        
        mStatisticsMBean =
            new DeploymentServiceStatistics(this, anEnv.getEnvironmentContext());   
        
        /*
         * Local initialization of this service.
         * Local routine is responsible for calling super.initModelSystemService(..).
         */
        initModelSystemService(anEnv.getEnvironmentContext());
        
        mTranslator = (StringTranslator) anEnv.getEnvironmentContext().
        getStringTranslator("com.sun.jbi.management");
        
        //register INITIAL mbean set:
        
           
        // add statistics mbean
        mInitialMBeans.replace(super.mStatisticsMBeanName,
            com.sun.jbi.management.system.DeploymentServiceStatisticsMBean.class,
            mStatisticsMBean);            
        mInitialMBeans.register();
        
        dplyRoot = sMContext.getJbiInstallRoot() + File.separator +
        "service-assemblies";                
    }
    
    /** local model init - called by constructor - create custom mbeans. */
    protected void initModelSystemService(com.sun.jbi.EnvironmentContext anEnv)
    {
        String loggerName = 
            com.sun.jbi.management.config.LoggerConfigurationFactory.DEPLOYMENT_LOGGER;
       
        Logger logger = Logger.getLogger(loggerName);
        
        //initialize the super.
        super.initModelSystemService(anEnv, logger, mJbiNameInfo);
        
        mStatisticsMBean.setLastRestartTime(new Date());        
        mStatisticsMBean.setEnabled();
        
        //add DeploymentService MBean to START/STOP mbean set:
        mStartMBeans.add(mDeployServiceMBeanName,
        com.sun.jbi.management.DeploymentServiceMBean.class, this);
    }
    
    /**
     * Deploy a Service Assembly (SA) to the JBI framework.
     * @param saZipURL The URL of the Service Assembly.
     * @return A string containing the status of
     * Service Assembly deployment including messages from components.
     * @throws Exception If failed to deploy an SA.
     */
    public String deploy(String saZipURL) throws Exception
    {
        String dplyRslt = null;
        List cmpTaskRslts = new ArrayList();
        boolean saDplyRslt = true;
        int numCmps = 0;
        int numScssDplyToCmps = 0;
        URL saUrl = null;
        EventNotifierCommon notifier =
            sMContext.getEnvironmentContext().getNotifier();
        
        try
        {
            if(saZipURL == null)
            {
                String errMsg = mTranslator.getString(
                LocalStringKeys.DS_CANNOT_DEPLOY_SA_ZIP_URL_NULL);
                String jbiExStr = buildFrmwkExMsg("deploy",
                null, errMsg);
                throw new Exception(jbiExStr);
            }
            saUrl = convertToProperURL(saZipURL);  
        }
        catch(Exception e)
        {
            throw e;
        }
        
        File ar = new File(saUrl.toURI());
        mLogger.log(Level.FINEST, "Deploying file : {0}", ar.getAbsolutePath());
        Archive saArchive = new Archive(ar, false);
        ServiceAssemblyDescriptor descr = new ServiceAssemblyDescriptor(saArchive.getJbiXml(false));
        String saName = descr.getName();
        
        if ( !mEnv.getPlatformContext().isAdminServer())
        {
            
            ServiceAssemblyInfoImpl saInfo = new ServiceAssemblyInfoImpl();
            saInfo.setName(saArchive.getJbiName());
            try
            {
                //add archive to repository if not present - repeated deployments
                ServiceAssemblyQuery saQuery = getRegistry().getServiceAssemblyQuery();
                if ( ! saQuery.getServiceAssemblies().contains(saName))
                {
                    getRegistry().getRepository().addArchive(saArchive);
                    getRegistry().getUpdater().addServiceAssembly(
                        saName, saArchive.getFileName(), saArchive.getUploadTimestamp());
                    saUrl = new File(saArchive.getPath()).toURL();
                } 
                else 
                {
                    File existingArchive = 
                        new File(getRegistry().getRepository().getArchive(
                            ArchiveType.SERVICE_ASSEMBLY, saName).getPath());
                    
                    boolean areArchivesIdentical = FileHelper.areFilesIdentical(existingArchive, ar);
                    if (!areArchivesIdentical)
                    {
                        String errMsg = mTranslator.getString(
                        LocalStringKeys.DS_SERVICE_ASSEMBLY_WITH_SAME_NAME_EXISTS, saName);
                        throw new Exception(errMsg);
                    }
                }
                    
            }
            catch ( JBIException jbiex)
            {
                MessageBuilder msgBuilder = new MessageBuilder(mTranslator);
                
                throw new JBIException(
                msgBuilder.buildExceptionMessage("deploy", jbiex));
            }
            
            ar.delete();
        }
        
        try
        {
            ServiceAssemblyInfo     saInfo = getServiceAssemblyInfo(saName, "domain");
            List   suList = saInfo.getServiceUnitList();
            DocumentBuilderFactory  dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder         db = dbf.newDocumentBuilder();
            
            for (ServiceUnitInfo su : suList)
            {
                String          suName = null;
                String          compName = null;
                ComponentState  cmpState = ComponentState.UNKNOWN;
                String          suRootPath = null;
                boolean         skipDeployment = false;
                
                try
                {              
                    suName     = su.getName();
                    compName   = su.getTargetComponent();
                    suRootPath = su.getFilePath();

                    mLogger.log(Level.FINE, "About to deploy service unit {0}", suName);

                    numCmps++;

                    String suJarAbsPath = getRegistry().getRepository().
                        getArchive(ArchiveType.SERVICE_UNIT, saName + java.io.File.separator + suName).getPath();
                    
                    cmpState = getComponentState(compName);
                    if (cmpState == ComponentState.UNKNOWN)
                    {
                        String errMsg = mTranslator.getString(
                        LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_UNIT_COMP_NOT_INSTALLED,
                        suName, compName);
                        throw new Exception(errMsg);
                    }
                    
                    if (cmpState == ComponentState.SHUTDOWN)
                    {
                        String errMsg = mTranslator.getString(
                        LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE,
                        suName, compName);
                        throw new Exception(errMsg);
                    }
                    
                    boolean isSURegistered =
                    sMContext.getServiceUnitRegistration().isServiceUnitRegistered(compName, suName);
                    
                    if(isSURegistered)
                    {
                        mLogger.log(Level.FINEST, "Service unit {0} already registered.", suName);
                        skipDeployment = true;
                    }
                
                    mLogger.log(Level.FINE, "Checking the service unit contents for service unit {0}", suName);
                    ServiceUnitInfo aSUInfo = getServiceUnitInfo(compName, suName);
                    if( (aSUInfo != null) && (!saName.equalsIgnoreCase(aSUInfo.getServiceAssemblyName())) )
                    {
                        String errMsg = mTranslator.getString(
                        LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_UNIT_DUPLICATE_SU_NAME,
                        suName, compName);
                        throw new Exception(errMsg);
                    }
                    
                    boolean isDuplicateSUContents = checkSUContents(
                    saName, compName, suName, suJarAbsPath);
                    
                    if(isDuplicateSUContents)
                    {
                        String errMsg = mTranslator.getString(
                        LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_UNIT_DUPLICATE_SU_CONTENTS,
                        suName, compName);
                        throw new Exception(errMsg);
                    }
                    
                }
                catch (Exception e)
                {
                    Element elem = getComponentResultXmlFragment(compName, "deploy", e);
                    cmpTaskRslts.add(elem);
                    
                    // Stop processing and try to deploy
                    // the next SU in the SA.
                    continue;
                }
                
                
                mLogger.log(Level.FINEST, "Invoking deploy operation for service unit {0} and component {1}", new Object[]{suName, compName});

                String cmpTaskRslt = null;
                try
                {
                    if (skipDeployment)
                    {
                        mLogger.log(Level.FINE, "Skipping deployment of  {0}", suName);  
                        numScssDplyToCmps++;        
                        // build a success component-task-result element
                        String locMsg = mTranslator.getString(
                                LocalStringKeys.DS_SERVICE_UNIT_ALREADY_DEPLOYED, suName);                        
                        String scssMsg = buildComponentStatusMsg(
                                compName, "deploy", suName, locMsg);
                        Document doc = db.parse(new InputSource(new StringReader(scssMsg)));
                        Element elem = DOMUtil.UTIL.getElement(doc, "component-task-result");
                        cmpTaskRslts.add(elem);                        
                    }
                    else
                    {
                        DeployerMBean deployer = getComponentDeployerInstance(compName);

                        if ( deployer != null )
                        {
                             dplyRslt = deployer.deploy(suName, suRootPath);
                        }
                        else
                        {
                            String errMsg = mTranslator.getString(
                                LocalStringKeys.DS_CANNOT_DEPLOY_SU_DEPLOYER_INSTANCE_NULL,
                                suName, compName, cmpState);
                                throw new Exception(errMsg);
                        }

                        String suRgstrnRslt = null;

                        boolean isSUDplymntScss = checkSUTaskRsltStatus(dplyRslt);
                        String dplyRsltWithWarning = null;
                        Document doc = null;

                        if(isSUDplymntScss)
                        {
                            // Emit a notification of the successful deploy
                            if ( null != notifier )
                            {
                                notifier.emitServiceUnitNotification(
                                    EventNotifierCommon.EventType.Deployed,
                                    suName, saName, compName, "");
                            }

                            suRgstrnRslt = registerServiceUnit(compName,
                            saName,
                            suName, suRootPath);

                            mLogger.log(Level.FINEST, "Registered service unit {0} for component {1} with result {2}", new Object[]{suName, compName, suRgstrnRslt});

                            if(suRgstrnRslt.equalsIgnoreCase("SUCCESS"))
                            {
                                doc = db.parse(new InputSource(new StringReader(dplyRslt)));
                            }
                            else
                            {
                                dplyRsltWithWarning = appendWarningToCmpRslt(suRgstrnRslt, dplyRslt);
                                doc = db.parse(new InputSource(
                                new StringReader(dplyRsltWithWarning)));
                            }
                            numScssDplyToCmps++;
                        }
                        else
                        {
                            doc = db.parse(new InputSource(new StringReader(dplyRslt)));
                        }

                        Element elem = DOMUtil.UTIL.getElement(doc, "component-task-result");
                        cmpTaskRslts.add(elem);
                    }
                
                }
                catch (DeploymentException e)
                {
                    Element elem = getComponentResultXmlFragment(compName, "deploy", e);
                    cmpTaskRslts.add(elem);
                }
            }
            
            // check to see if at least one service unit was deployed successfully

            if (numCmps > 0 && numScssDplyToCmps == 0)            
            {
                saDplyRslt = false;
            }
        }
        catch (DeploymentException de)
        {
            throw new Exception(de.getMessage());
        }
        catch (Exception e)
        {
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_ASSEMBLY, saUrl);
            String jbiTaskStr = buildFrmwkExMsg("deploy",
            e, errMsg);
            throw new Exception(jbiTaskStr);
        }
        
        String resp = buildResponse(cmpTaskRslts, saDplyRslt, "deploy", saName);
        
        if (!saDplyRslt)
        {
            mLogger.info(mTranslator.getString(
            LocalStringKeys.DS_DEPLOYMENT_FAILURE, saUrl));
            
            String saUnzipDir = null;
            
            if ( !mEnv.getPlatformContext().isAdminServer() )
            {
                // -- Complete failure to deploy
                // -- Remove from the local registry / repository
                try
                {
                    getRegistry().getRepository().removeArchive(ArchiveType.SERVICE_ASSEMBLY, saName);
                    getRegistry().getUpdater().removeServiceAssembly("domain", saName);
                }
                catch( JBIException jbiex)
                {
                    mLogger.warning(MessageHelper.getMsgString(jbiex));
                }
            }
            
            // deployment failure requires an exception to be thrown
            throw new Exception(resp);
        }
        String deployMsg = mTranslator.getString(
            LocalStringKeys.DS_DEPLOYMENT_SUCCESS, saUrl);
        mLogger.info(deployMsg);

        // Emit a notification of the successful deploy
        if ( null != notifier )
        {
            notifier.emitServiceAssemblyNotification(
                EventNotifierCommon.EventType.Deployed, saName, deployMsg);
        }

        try
        { 
            // If this is a redeploy the service assembly might be present under the instance.
            if ( !getRegistry().getServiceAssemblyQuery().getServiceAssemblies().contains(saName) )
            {   
                getRegistry().getUpdater().addServiceAssembly(saName);
                if ( isServiceAssemblyEmpty(saName) )
                {
                     getRegistry().getUpdater().setServiceAssemblyState(ServiceAssemblyState.SHUTDOWN, saName);
                }

            }
        }
        catch ( JBIException jbiex)
        {
            MessageBuilder msgBuilder = new MessageBuilder(mTranslator);
            
            throw new JBIException(
                msgBuilder.buildExceptionMessage("deploy", jbiex));
        }
        
        //create a new stats object
        mServiceAssemblyStats.put(saName, createNewSAStatsObject(saName));
        return resp;
    }
    
    
    /**
     * Undeploy a Service Assembly from the JBI framework.
     * @param saName - service assembly name
     * @return A string containing the status of
     * Service Assembly undeployment including messages from components.
     * @throws Exception if undeploy fails.
     */
    public String undeploy(String saName) throws Exception
    {
        //default force = false, keep = false ( keep is ignored on the instance )
        return undeploy(saName, false, false);
    }
    
    
    /**
     * Get list of deployed service units to the component.
     * @param componentName The name of the component.
     * @return A string array containing the list of
     * service units deployed to the component.
     * @throws Exception If component throws an exception
     */
    
    public String[] getDeployedServiceUnitList(String componentName) throws Exception
    {
        String[] suNameList = null;
        Element elem = null;
        
        try
        {
            MBeanServerConnection mbeanServer = getMBeanServerConnection();
            Object resultObject = getDeployerMBeanObjectName(componentName);
            if (resultObject == null)
            {
                throw new DeploymentException("LIFECYCLE_OBJECTNAME_IS_NULL");
            }
            ObjectName dplyrObjName = (ObjectName) resultObject;
            
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            try
            {
                Object rsltObject = mbeanServer.getAttribute(dplyrObjName,
                "Deployments");
                
                suNameList = (String []) rsltObject;
            }
            catch (MBeanException mbe)
            {
                DeploymentException de = (DeploymentException) mbe.getTargetException();
                String exMessage = de.getMessage();
                Document doc = db.parse(new InputSource(new StringReader(exMessage)));
                elem = DOMUtil.UTIL.getElement(doc, "component-task-result");
                throw de;
                
            }
        }
        catch (Exception e)
        {
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_CANNOT_GET_SERVICE_UNIT_LIST, componentName);
            String jbiTask = appendCmpExToFrmwkEx("getDeployedServiceUnitList",
            e, errMsg, elem);
            throw new Exception(jbiTask);
        }
        
        
        return suNameList;
    }
    
    /**
     * Get the status of deployed service unit.
     * @param componentName The name of the component.
     * @param serviceUnitName name of the service unit.
     * @return A boolean value indicating whether the
     * service unit is deployed or not.
     * @throws Exception If component throws an exception
     */
    public boolean isDeployedServiceUnit(String componentName, String serviceUnitName) throws Exception
    {
        return getServiceUnitInfo(componentName, serviceUnitName) != null;
    }
    
    /**
     * Get framework information on a service unit.
     * @param compName The ID of the component.
     * @param suName The ID of the service unit.
     * @return ServiceUnitInfo service unit information.
     */
    public ServiceUnitInfo getServiceUnitInfo(String compName, String suName)
    {
        ComponentInfo   cInfo;
        ServiceUnitInfo suInfo = null;
        List            suList;
        
        cInfo = getComponentQuery().getComponentInfo(compName);
        
        if (cInfo != null)
        {
            suList = cInfo.getServiceUnitList();
            for (Object suList1 : suList) {
                ServiceUnitInfo info = (ServiceUnitInfo) suList1;
                if (info.getName().equals(suName))
                {
                    suInfo = info;
                    break;
                }
            }
        }
        
        return suInfo;
    }
    
    private String appendCmpExToFrmwkEx(String methodName, Throwable ex,
    String errMsg, Element elem)
    {
        String jbiTask = null;
        String token = null;
        
        // FiX ME : STRIP ID FROM MSG and POPULATE TOKEN
        
        try
        {
            ManagementMessageHolder mmHolder = new ManagementMessageHolder("EXCEPTION_MSG");
            mmHolder.setTaskName(methodName);
            mmHolder.setTaskResult("FAILED");
            mmHolder.setExceptionObject(ex);
            mmHolder.setLocToken(1, token);
            mmHolder.setLocMessage(1, errMsg);
            String jbiTaskStr = mMImpl.buildCompleteExceptionMessage(mmHolder);
            
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(new StringReader(jbiTaskStr)));
            Element jbiTaskElem = DOMUtil.UTIL.getElement(doc, "jbi-task-result");
            Element impElem = (Element) doc.importNode(elem, true);
            jbiTaskElem.appendChild(impElem);
            StringWriter sw = new StringWriter();
            jbiTask = DOMUtil.UTIL.DOM2String(doc, sw);
        }
        catch(Exception e)
        {
            String statusMsg = mTranslator.getString(
            LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG, methodName);
            mLogger.warning(statusMsg);
        }
        
        return jbiTask;
        
    }
    
    private String buildFrmwkExMsg(String methodName, Throwable ex, String errMsg)
    {
        String jbiTaskStr = null;
        
        try
        {
            ManagementMessageHolder mmHolder = new ManagementMessageHolder("EXCEPTION_MSG");
            mmHolder.setTaskName(methodName);
            mmHolder.setTaskResult("FAILED");
            String token = MessageBuilder.getMessageToken(errMsg);
            mmHolder.setLocToken(1, token);
            String msg = MessageBuilder.getMessageString(errMsg);
            mmHolder.setLocMessage(1, msg);
            if(ex != null)
            {
                mmHolder.setExceptionObject(ex);
            }
            mmHolder.setFrameworkLocale("en_US");
            
            jbiTaskStr = mMImpl.buildCompleteExceptionMessage(mmHolder);
            
        }
        catch(Exception e)
        {
            String statusMsg = mTranslator.getString(
            LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG, methodName);
            mLogger.warning(statusMsg);
            
        }
        
        return jbiTaskStr;
    }
    
    /**
     * Get the status to see if SU can be deployed based on component state.
     * @param componentName The name of the component.
     * @return A boolean value indicating whether the
     * service unit can be deployed or not.
     */
    public boolean canDeployToComponent(String componentName)
    {
        ComponentState cmpStatus;
        boolean canDeploy = false;
        
        try
        {
            cmpStatus = getComponentState(componentName);
            if (cmpStatus == ComponentState.STARTED)
            {
                canDeploy = true;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        return canDeploy;
        
    }
    
    /**
     * Get the XML string indicating service unit deploy/undeploy status.
     * @param cmpStatus HashMap containing various elements from components.
     * @param rslt Overall result of deployment.
     * @param isDeployment Value indicating whether it's deployment or not.
     * @return A boolean value indicating whether the
     * Application sub-assembly unit is deployed or not.
     * @throws Exception If fails to build response string
     */
    private String buildResponse(List cmpTaskRslts, boolean rslt,
    String methodName, String saName) throws Exception
    {
        
        String respDoc = null;
        Document doc = null;
        Element rootElem = null;
        Element respElem = null;
        String taskRslt = null;
        
        try
        {
            
            String threadId = Thread.currentThread().getName();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.newDocument();
            rootElem = doc.createElement("jbi-task");
            rootElem.setAttribute("version", "1.0");
            rootElem.setAttribute(
            "xmlns", "http://java.sun.com/xml/ns/jbi/management-message");
            rootElem.setAttribute("xmlns:xsi",
            "http://www.w3.org/2001/XMLSchema-instance");
            rootElem.setAttribute("xsi:schemaLocation",
            "http://java.sun.com/xml/ns/jbi/management-message ./managementMessage.xsd");
            if (rslt)
            {
                taskRslt = "SUCCESS";
            }
            else
            {
                taskRslt = "FAILED";
            }
            
            ManagementMessageHolder mmHolder = new ManagementMessageHolder("STATUS_MSG");
            
            mmHolder.setTaskName(methodName);
            mmHolder.setTaskResult(taskRslt);
            mmHolder.setFrameworkLocale("en_US");
            
            respElem = mMImpl.buildFrameworkTaskStatusMessage(doc, mmHolder);
            
            doc.appendChild(rootElem);
            rootElem.appendChild(respElem);
            
            Iterator iter = cmpTaskRslts.iterator();
            
            while (iter.hasNext())
            {
                Element importedNode = (Element) iter.next();
                Element elem = (Element) doc.importNode(importedNode, true);
                respElem.appendChild(elem);
            }
            
            // -- Add a task status msg if deploy is a success / partial success
            if(rslt && ( methodName.equalsIgnoreCase("deploy") || methodName.equalsIgnoreCase("start") ) )
            {
                addTaskStatusMsg(doc, saName, isPartialSuccess(cmpTaskRslts), methodName);
            }
            
            StringWriter sw = new StringWriter();
            respDoc = DOMUtil.UTIL.DOM2String(doc, sw);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new DeploymentException("UNABLE_TO_CREATE_DEPLOY_RESPONSE", e);
        }
        
        return respDoc;
    }
    
    private void addTaskStatusMsg(Document doc, String saName, boolean isPartialSuccess, String opName) 
        throws Exception
    {
        // no need for a start succeeded message in case of complete success, since this is redundant.
        if ( !isPartialSuccess && "start".equals(opName) )
        {
           return;
        }

        try
        {
            Element jbiTaskElem = DOMUtil.UTIL.getElement(doc, "jbi-task");
            Element jbiTaskRsltElem = DOMUtil.UTIL.getElement(
            jbiTaskElem, "jbi-task-result");
            Element frmwkTaskRsltElem = DOMUtil.UTIL.getElement(
            jbiTaskRsltElem, "frmwk-task-result");
            Element frmwkTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
            frmwkTaskRsltElem, "frmwk-task-result-details");
            Element taskRsltDtlsElem = DOMUtil.UTIL.getElement(
            frmwkTaskRsltDtlsElem, "task-result-details");
            Element msgTypeElem = doc.createElement("message-type");
            Element taskStatMsgElem = doc.createElement("task-status-msg");
            Element msgLocInfoElem = doc.createElement("msg-loc-info");
            Element locTokenElem = doc.createElement("loc-token");
            Element locMsgElem = doc.createElement("loc-message");
            String infoMsg = null;
            if ( isPartialSuccess )
            {
                DOMUtil.UTIL.setTextData(msgTypeElem, "WARNING");
                if ( "deploy".equalsIgnoreCase(opName))
                {
                    infoMsg = mTranslator.getString(
                        LocalStringKeys.DS_DEPLOY_SCSS_WITH_WRNING_MSG, saName);
                }
                else if ( "start".equalsIgnoreCase(opName) )
                {
                    infoMsg = mTranslator.getString(
                        LocalStringKeys.DS_START_SCSS_WITH_WRNING_MSG, saName);
                }
            }
            else
            {
                if ( "deploy".equalsIgnoreCase(opName))
                {
                    DOMUtil.UTIL.setTextData(msgTypeElem, "INFO");
                    infoMsg = mTranslator.getString(
                        LocalStringKeys.DS_DEPLOY_SCSS_INFO_MSG, saName);
                }
            }
            taskRsltDtlsElem.appendChild(msgTypeElem);
            String token = MessageBuilder.getMessageToken(infoMsg);
            String msg = MessageBuilder.getMessageString(infoMsg);
            DOMUtil.UTIL.setTextData(locTokenElem, token);
            DOMUtil.UTIL.setTextData(locMsgElem, msg);
            msgLocInfoElem.appendChild(locTokenElem);
            msgLocInfoElem.appendChild(locMsgElem);
            taskStatMsgElem.appendChild(msgLocInfoElem);
            taskRsltDtlsElem.appendChild(taskStatMsgElem);
            
        }
        catch(Exception e)
        {
            throw e;
        }
    }
    
    /** returns the ObjectName for the lifecycle Mbean of this component.
     * @param aCompName  id of a binding or engine component
     * @return the ObjectName for the lifecycle Mbean.
     * @throws Exception If failed to lookup object name
     */
    public ObjectName getLifeCycleMBeanObjectName(String aCompName)
    throws Exception
    {
        try
        {
            MBeanNames mbn = sMContext.getMBeanNames();
            ObjectName adminName = mbn.getSystemServiceMBeanName(
            "AdminService", mbn.CONTROL_TYPE_ADMIN_SERVICE);
            MBeanServerConnection mbeanServer = getMBeanServerConnection();
            Object[] params = new Object[1];
            params[0] = aCompName;
            String[] sig = new String[1];
            sig[0] = "java.lang.String";
            Object rsltObject = mbeanServer.invoke(adminName,
            "getComponentByName", params, sig);
            return (ObjectName) rsltObject;
        }
        catch (Exception e)
        {
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_UNABLE_TO_FIND_LIFECYCLE_MBEAN_OBJECT_NAME, aCompName);
            String jbiTaskStr = buildFrmwkExMsg("getLifeCycleMBeanObjectName",
            e, errMsg);
            throw new Exception(jbiTaskStr);
        }
    }
    
    
    /**
     * Returns a list of Service Assemblies deployed to the JBI enviroment.
     * @return list of Service Assembly names
     * @throws Exception If failed to retrieve SA Ids
     */
    public String[] getDeployedServiceAssemblies() throws Exception
    {
        try 
        {
            ServiceAssemblyQuery saQuery = getRegistry().getServiceAssemblyQuery();
            List saNamesList = saQuery.getServiceAssemblies();
            String[] saNames = new String[saNamesList.size()];
            saNamesList.toArray(saNames);
            return saNames;            
        }
        catch (Exception e)
        {
            String errMsg = mTranslator.getString(
                LocalStringKeys.DS_UNABLE_TO_FIND_DEPLOYED_SERVICE_ASSEMBLY_NAMES);
            String jbiTaskStr = buildFrmwkExMsg("getDeployedServiceAssemblies", e, errMsg);
            throw new Exception(jbiTaskStr);
        }
    }
    
    
    /**
     * Returns a list of Service Assemblies that contain SUs
     * for the given component.
     * @param componentName Name of the component
     * @return list of Service Assembly names
     * @throws Exception If fails to retrieve SA Ids
     */
    public String[] getDeployedServiceAssembliesForComponent(String componentName)
    throws Exception
    {
        List saNameList = new ArrayList();
        
        try
        {

            ComponentInfo compInfo  = getComponentQuery().getComponentInfo(componentName);

            List suList = compInfo.getServiceUnitList();
            for(ServiceUnitInfo su : suList)
            {
                //ServiceUnitInfo su = (ServiceUnitInfo) suList.get(i);
                if ( !saNameList.contains(su.getServiceAssemblyName())){
                    saNameList.add(su.getServiceAssemblyName());
                }
            } 
        }
        catch (Exception e)
        {
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_UNABLE_TO_GET_SERVICE_ASSEMBLY_NAMES_FOR_COMPONENT,
            componentName);
            String jbiTaskStr = buildFrmwkExMsg("getDeployedServiceAssembliesForComponent",
            e, errMsg);
            throw new Exception(jbiTaskStr);
        }
        
        String[] saNameArray = new String[saNameList.size()];
        saNameList.toArray(saNameArray);
        saNameList = null;
        return saNameArray;
    }
    
    /**
     * Get the Service Assembly name for a specific service unit deployed to a 
     * specific component.
     * 
     * @param serviceUnitName - service unit identifier
     * @param componentName - component identifier
     * @return the parent service assembly name for the specified service unit
     * deployed to the specific component. If the service unit is not
     * deployed a null value is returned.
     */
    public String getServiceAssemblyName(String serviceUnitName, String componentName) 
            throws Exception{
        
        String serviceAssemblyName = null;

        ComponentInfo compInfo = getComponentQuery().getComponentInfo(componentName);

        if ( compInfo != null )
        {
            List suList = compInfo.getServiceUnitList();

            for ( ServiceUnitInfo suInfo : suList)
            {
                if ( suInfo.getName().equals(serviceUnitName) )
                {
                    serviceAssemblyName = suInfo.getServiceAssemblyName();
                }
            }
        }
        return serviceAssemblyName;
    }
    
    /**
     * Returns a list of components(to which SUs are targeted for)
     * in a Service Assembly.
     * @param saName name of the Service Assembly
     * @return list of component names
     * @throws Exception If fails to retrieve component Ids
     */
    public String[] getComponentsForDeployedServiceAssembly(String saName) throws Exception
    {
        try
        {
            List compNameList = new ArrayList();
            ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName, "domain");
            List suList = saInfo.getServiceUnitList();
            for (ServiceUnitInfo su : suList)
            {
                compNameList.add(su.getTargetComponent());
             }
            String[] compNameArray = new String[compNameList.size()];
            compNameList.toArray(compNameArray);
            return compNameArray;            
        }
        catch (DeploymentException de)
        {
            de.printStackTrace();
            throw new Exception(de.getMessage());
        }
        catch (Exception e)
        {
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_UNABLE_TO_FIND_COMPONENT_NAMES_FOR_SA, saName);
            String jbiTaskStr = buildFrmwkExMsg("getComponentsForDeployedServiceAssembly",
            e, errMsg);
            throw new Exception(jbiTaskStr);
        }        
    }
    
    
    
    /**
     * Returns the descriptor of Service Assembly (SA) deployed.
     * @param saName name of the service assembly
     * @return descriptor of Service Assembly (SA)
     * @throws Exception If fails to retrieve deployment descriptor
     */
    public String getServiceAssemblyDescriptor(String saName) throws Exception
    {
        String jbiXmlString = null;
        try
        {
            jbiXmlString = 
                    getRegistry().getGenericQuery().getServiceAssemblyDeploymentDescriptor(saName);
            return jbiXmlString;            
        }
        catch (Exception e)
        {
            e.printStackTrace();
            String errMsg = mTranslator.getString(LocalStringKeys.DS_SA_DESCRIPTOR_NOT_FOUND, saName);
            String jbiTaskStr = buildFrmwkExMsg("getServiceAssemblyDescriptor", e, errMsg);
            throw new Exception(jbiTaskStr);
        }

    }
    
    /**
     * Returns the descriptor of Service Unit(SU) deployed.
     * @param saName name of the service assembly
     * @param saName name of the service unit
     * @return descriptor of Service Unit(SU)
     * @throws Exception If fails to retrieve deployment descriptor
     */
    public String getServiceUnitDescriptor(String saName, String suName) throws UnsupportedOperationException
    {
	/* This operation is not implemented since the facade DeploymentService
	 * gets the service unit descriptor from the service assembly archive on
	 * the DAS directly.
	*/
	throw new UnsupportedOperationException();
    }
    
    /**
     * Get the actual state of the component from the ComponentLifeCycleMBean.
     * @param compName The ID of the component.
     * @return the component state, if the component is not installed a value of
     * ComponentState.UNKNOWN is returned.
     */
    public ComponentState getComponentState(String compName)
    {
        ObjectName compLCName = getComponentLifeCycleMBeanName(compName);
        ComponentState cmpStatus = ComponentState.UNKNOWN;
        
        if ( compLCName != null )
        {
            MBeanServer mbnServer = sMContext.getMBeanServer();
            
            try
            {
                String state  = (String) mbnServer.getAttribute(
                        compLCName, "CurrentState"); 

                cmpStatus = ComponentState.valueOfLifeCycleState(state);
            }
            catch (javax.management.JMException infex)
            {
                mLogger.warning(infex.toString());
            }
        }
        return cmpStatus;
    }
    
    /**
     * Get the actual state of a service unit.
     * @param compName The ID of the component.
     * @param suName The ID of the service unit.
     * @return int value indicating the service unit state.
     */
    public ServiceUnitState getActualServiceUnitState(String compName, String suName)
    {
        ServiceUnitState suState = ServiceUnitState.UNKNOWN;
        
        ComponentState compState = getComponentState(compName);
        
        // If the component is shutdown, the service unit is in the shutdown state.
        if ( compState == ComponentState.SHUTDOWN )
        {
            suState = ServiceUnitState.SHUTDOWN;
        }
        else if ( compState != ComponentState.UNKNOWN )
        {
            DeployerMBean deployer = getComponentDeployerInstance(compName);

            if ( deployer != null )
            {
                 suState = deployer.getServiceUnitState(suName);
            }
        }
        return suState;
    }
    
    /**
     * Builds a component-task-result XML fragment from the exception. 
     * @param taskName - task id 
     * @param compId   - component id
     * @param e - source Exception to build the component task result from 
     * @return the component-task-result DOM element.
     */
    private Element buildComponentExMsg(String taskName, String compId, Exception e)
    {
        Element elem = null;
        StringBuffer sb = new StringBuffer("");
        StackTraceElement[] stckTrElem = e.getStackTrace();
        if (stckTrElem != null)
        {
            for (StackTraceElement stckTrElem1 : stckTrElem) {
                String stckTrace = stckTrElem1.toString();
                sb.append(stckTrace);
                sb.append("\n");
            }
            
        }
        
        String[] msgParams = new String[1];
        msgParams[0] = "";
        ComponentMessageHolder cmpParams = new ComponentMessageHolder("EXCEPTION_MSG");
        cmpParams.setComponentName(compId);
        cmpParams.setTaskName(taskName);
        cmpParams.setTaskResult("FAILED");
        String errMsg = e.getMessage();
        if(errMsg.startsWith("JBI"))
        {
            cmpParams.setLocToken(1, MessageBuilder.getMessageToken(errMsg));
            String msg = MessageBuilder.getMessageString(errMsg);
            cmpParams.setLocMessage(1, msg);
        }
        else
        {
            cmpParams.setLocToken(1, "");
            cmpParams.setLocMessage(1, e.getMessage());
        }
        cmpParams.setLocParam(1, msgParams);
        cmpParams.setExceptionObject(e);
        cmpParams.setExceptionMessageType("ERROR");
        
        String cmpMsg = null;
        try
        {
            cmpMsg = mMImpl.buildComponentTaskExceptionMessage(cmpParams);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(
            new StringReader(cmpMsg)));
            elem = DOMUtil.UTIL.getElement(doc,
            "component-task-result");
        }
        catch (Exception cmpe)
        {
            cmpe.printStackTrace();
            String statusMsg = mTranslator.getString(
            LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG);
            mLogger.warning(statusMsg);
        }
        
        return elem;
        
    }
    
    
    public String registerServiceUnit(String compName, String saName,
    String suName, String suRootPath)
    throws Exception
    {
        String rgstrTaskStr = "SUCCESS";
        
        try
        {
            ServiceUnitRegistration suRegistration =
            sMContext.getServiceUnitRegistration();
            suRegistration.registerServiceUnit(compName, saName, suName, suRootPath);
            
        }
        catch(Throwable t)
        {
            t.printStackTrace();
            ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder("STATUS_MSG");
            cmpMsgHolder.setComponentName(compName);
            cmpMsgHolder.setTaskName("deploy");
            cmpMsgHolder.setTaskResult("SUCCESS");
            cmpMsgHolder.setStatusMessageType("WARNING");
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_REGISTER_SERVICE_UNIT_FAILED, suName);
            String token = MessageBuilder.getMessageToken(errMsg);
            cmpMsgHolder.setLocToken(1, token);
            String msg = MessageBuilder.getMessageString(errMsg);
            cmpMsgHolder.setLocMessage(1,msg);
            
            try
            {
                rgstrTaskStr = mMImpl.buildComponentMessage(cmpMsgHolder);
            }
            catch(Exception e)
            {
                throw e;
            }
        }
        
        return rgstrTaskStr;
        
        
    }
    
    /**
     * @param compName - target component for service unit unregistration
     * @param suName - name of service unit to unregister
     */
    public String unregisterServiceUnit(String compName, String suName)
    throws Exception
    {
        String unrgstrTaskStr = "SUCCESS";
        
        try
        {
            ServiceUnitRegistration suRegistration =
            sMContext.getServiceUnitRegistration();
            suRegistration.unregisterServiceUnit(compName, suName);
            
        }
        catch(Throwable t)
        {
            t.printStackTrace();
            ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder("STATUS_MSG");
            cmpMsgHolder.setComponentName((String)compName);
            cmpMsgHolder.setTaskName("deploy");
            cmpMsgHolder.setTaskResult("SUCCESS");
            cmpMsgHolder.setStatusMessageType("WARNING");
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_UNREGISTER_SERVICE_UNIT_FAILED, suName);
            String token = MessageBuilder.getMessageToken(errMsg);
            cmpMsgHolder.setLocToken(1, token);
            String msg = MessageBuilder.getMessageString(errMsg);
            cmpMsgHolder.setLocMessage(1,msg);
            
            try
            {
                unrgstrTaskStr = mMImpl.buildComponentMessage(cmpMsgHolder);
            }
            catch(Exception e)
            {
                throw e;
            }
        }
        
        return unrgstrTaskStr;
        
        
    }
    
    
    /**
     * Shut down the DeploymentService.
     * @exception javax.jbi.JBIException if the item fails to shut down.
     */
    public void shutDown() throws javax.jbi.JBIException
    {
        super.shutDown();
    }
    
    private boolean checkSUTaskRsltStatus(String suDeployRslt) throws Exception
    {
        boolean taskRslt = false;
        
        try
        {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(new StringReader(suDeployRslt)));
            Element compTaskRsltElem = DOMUtil.UTIL.getElement(doc, "component-task-result");
            Element cmpTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
            compTaskRsltElem, "component-task-result-details");
            Element taskRsltDtlsElem = DOMUtil.UTIL.getElement(
            cmpTaskRsltDtlsElem, "task-result-details");
            Element rsltElem = DOMUtil.UTIL.getElement(taskRsltDtlsElem, "task-result");
            String dplyRslt = DOMUtil.UTIL.getTextData(rsltElem);
            if(dplyRslt.equalsIgnoreCase("SUCCESS"))
                taskRslt = true;
            else
                taskRslt = false;
        }
        catch(Exception e)
        {
            throw e;
        }
        
        return taskRslt;
        
    }
    
    private String appendWarningToCmpRslt(String suRgstrnRslt, String suDplyRslt)
    throws Exception
    {
        String cmpTaskRsltStr = null;
        
        try
        {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(new StringReader(suDplyRslt)));
            Element compTaskRsltElem = DOMUtil.UTIL.getElement(doc, "component-task-result");
            Element cmpTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
            compTaskRsltElem, "component-task-result-details");
            Element taskRsltDtlsElem = DOMUtil.UTIL.getElement(
            cmpTaskRsltDtlsElem, "task-result-details");
            Element mtElem = DOMUtil.UTIL.getElement(
            taskRsltDtlsElem, "message-type");
            Element msgTypeElem = null;
            if(mtElem == null)
            {
                msgTypeElem = doc.createElement("message-type");
                DOMUtil.UTIL.setTextData(msgTypeElem, "WARNING");
                taskRsltDtlsElem.appendChild(msgTypeElem);
            }
            
            Document suRgstrnDoc = db.parse(new InputSource(new StringReader(suRgstrnRslt)));
            Element rgstrnCmpTaskRsltElem = DOMUtil.UTIL.getElement(suRgstrnDoc, "component-task-result");
            Element rgstrnCmpTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
            rgstrnCmpTaskRsltElem, "component-task-result-details");
            Element rgstrnTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
            rgstrnCmpTaskRsltDtlsElem, "task-result-details");
            Element statusMsgElem = DOMUtil.UTIL.getElement(rgstrnTaskRsltDtlsElem, "task-status-msg");
            Element impElem = (Element) doc.importNode(statusMsgElem, true);
            taskRsltDtlsElem.appendChild(impElem);
            
            StringWriter sw = new StringWriter();
            cmpTaskRsltStr = DOMUtil.UTIL.DOM2String(doc, sw);
        }
        catch(Exception e)
        {
            throw e;
        }
        
        return cmpTaskRsltStr;
    }
    
    private String buildComponentStatusMsg(String compName, String methodName,
    String suName)
    {
        String compStatusMsg = null;
        
        ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder("STATUS_MSG");
        cmpMsgHolder.setComponentName(compName);
        cmpMsgHolder.setTaskName(methodName);
        cmpMsgHolder.setTaskResult("SUCCESS");
        
        String locMsg = mTranslator.getString(LocalStringKeys.DS_SU_LIFECYCLE_OP_SUCCESS,
        methodName, suName);
        cmpMsgHolder.setStatusMessageType("INFO");
        cmpMsgHolder.setLocToken(1, MessageBuilder.getMessageToken(locMsg));
        cmpMsgHolder.setLocMessage(1, MessageBuilder.getMessageString(locMsg));
        cmpMsgHolder.setLocParam(1, new String[]
        {methodName, suName});
        
        try
        {
            compStatusMsg = mMImpl.buildComponentMessage(cmpMsgHolder);
        }
        catch(Exception exObj)
        {
            String statusMsg = mTranslator.getString(
            LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG);
            mLogger.warning(statusMsg);
        }
        
        return compStatusMsg;
    }
    
    /**
     * This method is used to build a component task result status 
     * message with SUCCESS as the status and with the given information
     * string
     * @param compName the component name
     * @param methodName the task id
     * @param suName the service unit name
     * @param info the string that should go in the message
     */
    private String buildComponentStatusMsg(
            String compName, 
            String methodName, 
            String suName,
            String info)
    {
        String compStatusMsg = null;
        
        ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder("STATUS_MSG");
        cmpMsgHolder.setComponentName(compName);
        cmpMsgHolder.setTaskName(methodName);
        cmpMsgHolder.setTaskResult("SUCCESS");
        
        cmpMsgHolder.setStatusMessageType("INFO");
        cmpMsgHolder.setLocToken(1, MessageBuilder.getMessageToken(info));
        cmpMsgHolder.setLocMessage(1, MessageBuilder.getMessageString(info));
        cmpMsgHolder.setLocParam(1, new String[]
        {methodName, suName});
        
        try
        {
            compStatusMsg = mMImpl.buildComponentMessage(cmpMsgHolder);
        }
        catch(Exception exObj)
        {
            String statusMsg = mTranslator.getString(
            LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG);
            mLogger.warning(statusMsg);
        }
        
        return compStatusMsg;
    }    
    
    /**
     * Get the MBean Server
     *
     * @return thge MBean Server reference.
     */
    public MBeanServerConnection getMBeanServerConnection()
    {
        return sMContext.getCentralMBeanServer();
    }
    
    
    /**
     * Starts the service assembly and puts it in
     * STARTED state.
     * @param serviceAssemblyName - name of the service
     *                              assembly.
     * @return Result/Status of this operation.
     * @throws Exception if operation fails.
     *
     */
    public String start(String serviceAssemblyName) throws Exception
    {
        HashMap infoMsgElems = null;
        String  saState = getState(serviceAssemblyName);
        
        if(!saState.equalsIgnoreCase(DeploymentServiceMBean.STARTED))
        {
            infoMsgElems = activateConnections(serviceAssemblyName);
        }
        // for start force = false
        String stateChangeRslt = startServiceAssembly(serviceAssemblyName);
        String jbiTaskStr = appendMsgsToTaskRslt(stateChangeRslt, infoMsgElems, "WARNING");
        return jbiTaskStr;
    }
    
    /**
     * Stops the service assembly and puts it in
     * STOPPED state.
     * @param serviceAssemblyName - name of the service
     *                              assembly.
     * @return Result/Status of this operation.
     * @throws Exception if operation fails.
     *
     */
    public String stop(String serviceAssemblyName) throws Exception
    {
        HashMap infoMsgElems = null;
        String  saState = getState(serviceAssemblyName);
        boolean isStarted = false;
        
        if(saState.equalsIgnoreCase(DeploymentServiceMBean.STARTED))
        {
            isStarted = true;
        }
        else if(saState.equalsIgnoreCase(DeploymentServiceMBean.SHUTDOWN))
        {
            String errMsg = mTranslator.getString(
            LocalStringKeys.DS_CANNOT_STOP_SA_SHUTDOWN_SA_STATE,
            serviceAssemblyName, saState);
            String jbiExStr = buildFrmwkExMsg("stop", null, errMsg);
            throw new Exception(jbiExStr);
        }
        
        return stopServiceAssembly(serviceAssemblyName, isStarted);
    }
    
    /**
     * Shutdown the service assembly and puts it in
     * SHUTDOWN state.
     * @param serviceAssemblyName - name of the service
     *                              assembly.
     * @return Result/Status of this operation.
     * @throws Exception if operation fails.
     *
     */
    public String shutDown(String serviceAssemblyName) throws Exception
    {
        // default force = false
        return shutDown(serviceAssemblyName, false);
    }
    
    /* Returns the state of service assembly.
     *
     * @param serviceAssemblyName - name of the service assembly.
     * @return State of the service assembly.
     * @throws Exception if operation fails.
     *
     */
    public String getState(String serviceAssemblyName) throws Exception
    {
        String saState = null;
        try
        {
            ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(serviceAssemblyName);
            
            if ( saInfo != null )
            {
                List suStates = new ArrayList();

                List suList = saInfo.getServiceUnitList();
                for ( ServiceUnitInfo suInfo : suList )
                {
                    String suName          = suInfo.getName();
                    String targetComponent = suInfo.getTargetComponent();
                    
                    ServiceUnitState suState = getActualServiceUnitState(targetComponent,
                        suName);
                     suStates.add( suState );       
                }
            
                if ( !suStates.isEmpty() )
                {
                    ServiceAssemblyState 
                        state = ServiceAssemblyState.computeServiceAssemblyState(suStates);
                
                    saState = ServiceAssemblyState.convertState(state);
                }
                else
                {
                    // -- This could be a service assembly with zero service units
                    //    get the state from the service assembly element
                    if ( isServiceAssemblyEmpty(serviceAssemblyName) )
                    {
                       ServiceAssemblyState state = getServiceAssemblyInfo(serviceAssemblyName).getStatus(); 
                       saState = ServiceAssemblyState.convertState(state);
                    }
                } 
            }
        }
        catch(Exception e)
        {
            if (!e.getMessage().startsWith("
     * If the service unit is deployed to the component then one of the states :
     * "Started", "Stopped" or "Shutdown" is returned. 
     *
     * @return the actual state of the deployed service unit or "Unknown". 
     * @param componentName - the component name
     * @param serviceUnitName - name of the service unit
     * @exception javax.jbi.JBIException if the component is not installed or if the 
     * service unit is not deployed to the component.
     * @see javax.jbi.management.DeploymentServiceMBean
     */
    public String getServiceUnitState(String componentName, String serviceUnitName) 
        throws javax.jbi.JBIException
    {
        ServiceUnitState suState = getActualServiceUnitState(componentName, 
            serviceUnitName);
        return ServiceUnitState.convertState(suState);
    }
    
    
    /**
     * Deploy a Service Assembly from the Repository. 
     * 
* This is a NOP. * * @param serviceAssemblyName - name of the registered service assembly. * @return a status management message with details on the service assembly deployment. * @exception javax.jbi.JBIException if the service assembly is not registered or * deploy fails. */ public String deployFromRepository(String serviceAssemblyName) throws javax.jbi.JBIException { // nop return serviceAssemblyName; } /** * Undeploys the given Service Assembly from the JBI environment. * * @param serviceAssemblyName name of the Service Assembly that is to be * undeployed; must be non-null and non-empty * @param force if this flag is set to true any undeployment errors thrown * from the component will be ignored as the service assembly is forcefully * undeployed. * @return Result/Status of the current undeployment; must conform to * JBI management result/status XML schema; must be non-null and * non-empty * @exception Exception if compelete undeployment fails */ public String undeploy(String serviceAssemblyName, boolean force) throws Exception { // default keep = false, actually keep is a don't care on the instance return undeploy(serviceAssemblyName, force, false); } /** * Undeploys the given Service Assembly from the JBI environment. * * @param saName name of the Service Assembly that is to be * undeployed; must be non-null and non-empty * @param force if this flag is set to true any undeployment errors thrown * from the component will be ignored as the service assembly is forcefully * undeployed. * @param keep if true the service assembly archive should not be removed * from the domain. If false the archive is removed if the service * assembly is not deployed on any instances. This flag is ignored on * the instance. * @return Result/Status of the current undeployment; must conform to * JBI management result/status XML schema; must be non-null and * non-empty * @exception Exception if compelete undeployment fails */ public String undeploy(String saName, boolean force, boolean keep) throws Exception { String jbiXmlPath = null; String undplyRslt = null; Object[] params = null; List cmpTaskRslts = new ArrayList(); boolean saUnDplyRslt = true; EventNotifierCommon notifier = sMContext.getEnvironmentContext().getNotifier(); try { // Get information on the service assembly deployed to the instance. ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName); List suList = saInfo.getServiceUnitList(); int numOfSUs = suList.size(); int numOfSUsUndeployed = 0; for (ServiceUnitInfo su : suList) { String suName = su.getName(); String compName = su.getTargetComponent(); String suRootPath = su.getFilePath(); ComponentState cmpState = ComponentState.UNKNOWN; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); try { // check to make sure SU has been deployed to component if (!isDeployedServiceUnit(compName, suName)) { mLogger.log(Level.FINE, "Service unit {0} has not been deployed to component {1} -- skipping undeploy", new Object[]{suName, compName}); numOfSUsUndeployed++; continue; } cmpState = getComponentState(compName); if (cmpState == ComponentState.UNKNOWN) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_UNDEPLOY_SERVICE_UNIT_COMP_NOT_INSTALLED, suName, compName); throw new Exception(errMsg); } /** * If the forced flag is set to true, a service assembly can be * undeployed even when the component is shutdown */ if (cmpState == ComponentState.SHUTDOWN && !force) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE, suName, compName); throw new Exception(errMsg); } } catch (Exception e) { mLogger.warning(MessageHelper.getMsgString(e)); Element elem = getComponentResultXmlFragment(compName, "undeploy", e); cmpTaskRslts.add(elem); // Stop processing and try to undeploy // the next SU in the SA. continue; } try { DeployerMBean deployer = getComponentDeployerInstance(compName); if ( deployer != null ) { undplyRslt = deployer.undeploy(suName, suRootPath, force); } else { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_UNDEPLOY_SU_DEPLOYER_INSTANCE_NULL, suName, compName, cmpState); throw new Exception(errMsg); } String suUnRgstrnRslt = null; boolean isSUUnDplymntScss = checkSUTaskRsltStatus(undplyRslt); if(isSUUnDplymntScss) { // Emit a notification of the successful undeploy if ( null != notifier ) { notifier.emitServiceUnitNotification( EventNotifierCommon.EventType.Undeployed, suName, saName, compName, ""); } /** * The force flag does not have to be propagated to the * unregisterServiceUnit method, since that only * (a) removes the service unit from the cached components * service unit list * (b) removes the service unit entry from the installed * component in the registry * Since both (a) and (b) do not interact with the * actual JBI Component, we do not need to propagate the force flag */ suUnRgstrnRslt = unregisterServiceUnit(compName, suName); if(!suUnRgstrnRslt.equalsIgnoreCase("SUCCESS")) { undplyRslt = appendWarningToCmpRslt(suUnRgstrnRslt, undplyRslt); } else { // service unit undeployed and unregistered successfully numOfSUsUndeployed++; } } Document doc = db.parse(new InputSource (new StringReader(undplyRslt))); Element elem = DOMUtil.UTIL.getElement(doc, "component-task-result"); cmpTaskRslts.add(elem); } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, "undeply", e); cmpTaskRslts.add(elem); } if ( !mEnv.getPlatformContext().isAdminServer() ) { try { DirectoryUtil.deleteDir((String)params[1]); } catch(Exception exObj) { File deleteMe = new File(suRootPath, PATH_TO_DELETE_ME_FILE); try { FileOutputStream fos = new FileOutputStream(deleteMe); fos.close(); } catch (IOException ioe) { String errMsg = mTranslator.getString( LocalStringKeys.DS_DIRECTORY_NOT_MARKED, suRootPath, ioe.getMessage()); mLogger.warning(errMsg); } String errMsg = mTranslator.getString( LocalStringKeys.DS_DIRECTORY_NOT_REMOVED, suRootPath); mLogger.warning(errMsg); moveToTrash(suRootPath); /* String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_DELETE_SU_ROOT_PATH, suRootPath, suName); mLogger.warning(errMsg); */ } } } if ( numOfSUsUndeployed < numOfSUs) { saUnDplyRslt = false; } } catch (DeploymentException de) { throw new Exception(de.getMessage()); } catch (Exception e) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_UNDEPLOY_SERVICE_ASSEMBLY, saName); String jbiTaskStr = buildFrmwkExMsg("undeploy", e, errMsg); throw new Exception(jbiTaskStr); } if (saUnDplyRslt) { String mSAUnzipDir = null; if ( !mEnv.getPlatformContext().isAdminServer() ) { try { // -- Remove from the local registry / repository getRegistry().getRepository().removeArchive(ArchiveType.SERVICE_ASSEMBLY, saName); getRegistry().getUpdater().removeServiceAssembly("domain", saName); } catch(JBIException jex) { mLogger.warning(MessageHelper.getMsgString(jex)); } } } String resp = buildResponse(cmpTaskRslts, saUnDplyRslt, "undeploy", saName); if (saUnDplyRslt) { String statusMsg = mTranslator.getString( LocalStringKeys.DS_UNDEPLOYMENT_SUCCESS, saName); mLogger.info(statusMsg); // Emit a notification of the successful undeploy if ( null != notifier ) { notifier.emitServiceAssemblyNotification( EventNotifierCommon.EventType.Undeployed, saName, statusMsg); } try { // Remove the service assembly from this instance getRegistry().getUpdater().removeServiceAssembly(saName); } catch ( JBIException jbiex) { MessageBuilder msgBuilder = new MessageBuilder(mTranslator); throw new JBIException( msgBuilder.buildExceptionMessage("deploy", jbiex)); } //remove the statistics object corresponding to this SA removeStatsObject(saName); return resp; } else { String statusMsg = mTranslator.getString( LocalStringKeys.DS_UNDEPLOYMENT_FAILURE, saName); mLogger.warning(statusMsg); //remove the statistics object corresponding to this SA removeStatsObject(saName); // undeployment failure requires an exception to be thrown throw new Exception(resp); } } /** * Shut down the service assembly. * * @param serviceAssemblyName name of the assembly to be shut down; must be * non-null and non-empty * @param force if this flag is true, the service assembly is shutdown forcefully. * Any exceptions thrown by the component for service unit shutdown are ignored. * @return result / status string giving the results of shutting down * each service unit in the assembly; must be non-null and non-empty * @exception Exception if there is no such assembly * @exception Exception if the assembly fails to shut down */ public String shutDown(String serviceAssemblyName, boolean force) throws Exception { String saState = getState(serviceAssemblyName); if(saState.equalsIgnoreCase(DeploymentServiceMBean.STARTED)) { // Need to stop the SA before it is shutdown stopServiceAssembly(serviceAssemblyName, true); } return stopShutDownServiceAssembly("shutDown", serviceAssemblyName, force); } /*---------------------------------------------------------------------------------*\ * Private Helpers * \*---------------------------------------------------------------------------------*/ /** This method rolls back SU states to SHUTDOWN as a result of a * failed start operation. This prevents a situation where an SU is * not successfully started, but it remains in a STOPPED (e.g. init) * instead of the expected SHUTDWON state. */ private void rollbackSUInits(List susToRollBack) { try { for ( ServiceUnitInfo su : susToRollBack ) { String suName = su.getName(); try { DeployerMBean deployer = getComponentDeployerInstance(su.getTargetComponent()); deployer.shutDown(suName); } catch(Exception e) { Element elem = getComponentResultXmlFragment(su.getTargetComponent(), "rollbackSUInits", e); Document doc = mMImpl.createDocument(); doc.appendChild(doc.importNode(elem,true)); StringWriter sw = new StringWriter(); String jbiExStr = DOMUtil.UTIL.DOM2String(doc, sw); mLogger.warning(jbiExStr); } } } catch(Exception e) { String jbiExStr = buildFrmwkExMsg("rollbackSUInits", e, e.getMessage()); mLogger.warning(jbiExStr); } } /** * @param lifecycle operation name - stop/shutDown * @param saName - name of service assembly to be targeted * @param force - if true the state change is forceful ( applies only when the * operation is stop/shutDown ) */ String stopShutDownServiceAssembly(String saLifecycleMthdName, String saName, boolean force) throws Exception { EventNotifierCommon notifier = sMContext.getEnvironmentContext().getNotifier(); //store the beginning time Date beginTime = new Date(); Map suTimes = new HashMap(); List cmpTaskRslts = new ArrayList(); boolean saStateChangeRslt = true; try { int operationCount = 0; int successCount = 0; ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName); List suList = saInfo.getServiceUnitList(); if ( isServiceAssemblyEmpty(saName) ) { ServiceAssemblyState saState = ( saLifecycleMthdName.equals("stop") ? ServiceAssemblyState.STOPPED : ServiceAssemblyState.SHUTDOWN ); getRegistry().getUpdater().setServiceAssemblyState(saState, saName); return buildResponse(cmpTaskRslts, saStateChangeRslt, saLifecycleMthdName, saName); } for ( ServiceUnitInfo su : suList ) { String suName = su.getName(); String compName = su.getTargetComponent(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); try { if (!isDeployedServiceUnit(compName, suName)) { mLogger.log(Level.FINE, "Service unit {0} is not deployed to component {1} : ignoring command {2}", new Object[]{suName, compName, saLifecycleMthdName}); continue; } ComponentState cmpState = getComponentState(compName); if (cmpState == ComponentState.UNKNOWN) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_NOT_INSTALLED, suName, compName); throw new Exception(errMsg); } if (cmpState == ComponentState.SHUTDOWN) { continue; } } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, saLifecycleMthdName, e); cmpTaskRslts.add(elem); // Stop processing and try to change the state // of the next SU in the SA. continue; } try { DeployerMBean deployer = getComponentDeployerInstance(compName); if (getActualServiceUnitState(compName, suName) != ServiceUnitState.SHUTDOWN) { if (saLifecycleMthdName.equalsIgnoreCase("stop")) { long suStopTimeBegin = System.currentTimeMillis(); ++operationCount; deployer.stop(suName); ++successCount; suTimes.put(suName, System.currentTimeMillis() - suStopTimeBegin); } else if (saLifecycleMthdName.equalsIgnoreCase("shutDown")) { long suShutdownTimeBegin = System.currentTimeMillis(); ++operationCount; deployer.shutDown(suName, force); ++successCount; suTimes.put(suName, System.currentTimeMillis() - suShutdownTimeBegin); } } // build a success component-task-result element String scssMsg = buildComponentStatusMsg(compName, saLifecycleMthdName, suName); Document doc = db.parse(new InputSource (new StringReader(scssMsg)));; Element elem = DOMUtil.UTIL.getElement(doc, "component-task-result"); cmpTaskRslts.add(elem); } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, saLifecycleMthdName, e); cmpTaskRslts.add(elem); } } // stop/shutdown is only successful if all operations succeed if (successCount < operationCount) { saStateChangeRslt = false; } } catch (Exception e) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SERVICE_ASSEMBLY_STATE, saName); String jbiTaskStr = buildFrmwkExMsg(saLifecycleMthdName,e, errMsg); throw new Exception(jbiTaskStr); } String resp = buildResponse(cmpTaskRslts, saStateChangeRslt, saLifecycleMthdName, null); if(!saStateChangeRslt) { // operation failed completely, throw an exception with result text throw new Exception(resp); } updateStatistics(saName, saLifecycleMthdName, beginTime, new Date(), suTimes); // Emit a notification of the successful operation if ( null != notifier ) { notifier.emitServiceAssemblyNotification( (saLifecycleMthdName.equals("stop") ? EventNotifierCommon.EventType.Stopped : EventNotifierCommon.EventType.ShutDown), saName, ""); } return resp; } /** * Start a Service Assembly. All the Service Units are first initialized and then * started. * * From the list of deployed service units only those service units are started, * which : *
  • *
      are deployed
    *
      are not already started
    *
      the target component is installed
    *
      the target component is not in the "Shutdown" state
    *
  • *
    * This operation first filters out the service units to be started * * @param saName - name of service assembly to be targeted */ String startServiceAssembly(String saName) throws Exception { // Get time this method was entered Date beginTime = new Date(); Map suTimes = new HashMap(); String saLifecycleMthdName = "start"; List cmpTaskRslts = new ArrayList(); boolean saStateChangeRslt = true; EventNotifierCommon notifier = sMContext.getEnvironmentContext().getNotifier(); int operationCount = 0; int successCount = 0; try { ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName); List suList = saInfo.getServiceUnitList(); List susToInitialize = new ArrayList(); List susToStart = new ArrayList(); List susAlreadyStarted = new ArrayList(); List susToRollBack = new ArrayList(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); if ( isServiceAssemblyEmpty(saName) ) { getRegistry().getUpdater().setServiceAssemblyState(ServiceAssemblyState.STARTED, saName); return buildResponse(cmpTaskRslts, saStateChangeRslt, saLifecycleMthdName, saName); } for ( ServiceUnitInfo su : suList ) { String suName = su.getName(); String compName = su.getTargetComponent(); try { if (!isDeployedServiceUnit(compName, suName)) { mLogger.log(Level.FINE, "Service unit {0} is not deployed to component {1} : ignoring command {2}", new Object[]{suName, compName, saLifecycleMthdName}); continue; } ComponentState cmpState = getComponentState(compName); if (cmpState == ComponentState.UNKNOWN) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_NOT_INSTALLED, suName, compName); throw new Exception(errMsg); } if (cmpState == ComponentState.SHUTDOWN) { // this counts as a failed operation, so increment the op counter ++operationCount; String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE, suName, compName); throw new Exception(errMsg); } } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, saLifecycleMthdName, e); cmpTaskRslts.add(elem); // Stop processing and try to change the state // of the next SU in the SA. continue; } ServiceUnitState currSuState = getActualServiceUnitState(compName, suName); switch ( currSuState ) { case STARTED: // -- Service unit already started counts as success; susAlreadyStarted.add(su); ++successCount; break; case STOPPED: // -- No need to init, only start this service unit susToStart.add(su); break; case SHUTDOWN : // -- Need to init and start the service unit susToInitialize.add(su); break; default : continue; } } // -- Now initialize all the service units ( this is fix for CR 6520614 ) // -- which are to be started first, only sus which were Shutdown are initialized. for ( ServiceUnitInfo su : susToInitialize ) { String suName = su.getName(); String compName = su.getTargetComponent(); try { // -- increment op counter for each su life cycle operation ++operationCount; /* At this point we have verfied that the Component is installed * the DeployerInstance cannot be null, since it is available * once the component is installed ( so is available when component * is shutdown too ) */ DeployerMBean deployer = getComponentDeployerInstance(compName); long suInitTime = System.currentTimeMillis(); deployer.init(su.getName(), su.getFilePath()); suTimes.put(suName, System.currentTimeMillis() - suInitTime); // -- start only initialized service units. susToStart.add(su); // -- if start fails then need to rollback to state before : Shutdown susToRollBack.add(su); } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, saLifecycleMthdName, e); cmpTaskRslts.add(elem); } } // -- Start the service units for ( ServiceUnitInfo su : suList ) { String suName = su.getName(); String compName = su.getTargetComponent(); try { if (susToStart.contains(su)) { // increment op counter for each SU life cycle operation ++operationCount; DeployerMBean deployer = getComponentDeployerInstance(compName); Long suInitTime = suTimes.get(suName); if ( null == suInitTime ) { suInitTime = new Long(0); } long suStartTime = System.currentTimeMillis(); deployer.start(suName); suTimes.put(suName, (System.currentTimeMillis() - suStartTime) + suInitTime); if ( susToRollBack.contains(su)) { // -- Start succeeded, no need to rollback this su susToRollBack.remove(su); } // if we made it here, the operation was successful ++successCount; String scssMsg = buildComponentStatusMsg(compName, saLifecycleMthdName, suName); Document doc = db.parse(new InputSource(new StringReader(scssMsg)));; Element elem = DOMUtil.UTIL.getElement(doc, "component-task-result"); cmpTaskRslts.add(elem); } else if (susAlreadyStarted.contains(su)) { // For SUs that are already in started state, add a component task result // that says SU already started String locMsg = mTranslator.getString( LocalStringKeys.DS_SERVICE_UNIT_ALREADY_STARTED, suName); String scssMsg = buildComponentStatusMsg( compName, saLifecycleMthdName, suName, locMsg); Document doc = db.parse( new InputSource( new StringReader(scssMsg)));; Element elem = DOMUtil.UTIL.getElement(doc, "component-task-result"); cmpTaskRslts.add(elem); } } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, saLifecycleMthdName, e); cmpTaskRslts.add(elem); } } // start is successful if at least one operation succeeds if (operationCount > 0 && successCount == 0) { saStateChangeRslt = false; } /** * If any service units which were in the Shutdown state could not be started * successfully, they need to be Shutdown again since they might be in the * Stopped state */ if ( !susToRollBack.isEmpty() ) { rollbackSUInits(susToRollBack); } } catch (Exception e) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SERVICE_ASSEMBLY_STATE, saName); String jbiTaskStr = buildFrmwkExMsg(saLifecycleMthdName, e, errMsg); throw new Exception(jbiTaskStr); } String resp = buildResponse(cmpTaskRslts, saStateChangeRslt, saLifecycleMthdName, saName); if(!saStateChangeRslt) { // operation failed completely, throw an exception with result text throw new Exception(resp); } //update statistics updateStatistics(saName, START, beginTime, new Date(), suTimes); // Emit a notification of the successful start if ( operationCount > 0 && null != notifier ) { notifier.emitServiceAssemblyNotification( EventNotifierCommon.EventType.Started, saName, ""); } return resp; } HashMap getConnectionsInfo(Element connectionElem, String saName) throws DeploymentException { HashMap connInfo = new HashMap(); try { QName intrfName = null; QName fromSvc = null; String fromEndpoint = null; QName toSvc = null; String toEndpoint = null; Element consumerElem = DOMUtil.UTIL.getElement( connectionElem, "consumer"); Element providerElem = DOMUtil.UTIL.getElement( connectionElem, "provider"); intrfName = DOMUtil.UTIL.getQualifiedAttributeValue( consumerElem, "interface-name"); if(intrfName == null || intrfName.toString().equals("")) { fromSvc = DOMUtil.UTIL.getQualifiedAttributeValue( consumerElem, "service-name"); fromEndpoint = DOMUtil.UTIL.getAttribute(consumerElem, "endpoint-name"); connInfo.put("from-service", fromSvc); connInfo.put("from-endpoint", fromEndpoint); } else { connInfo.put("interface-name", intrfName); } toSvc = DOMUtil.UTIL.getQualifiedAttributeValue( providerElem, "service-name"); toEndpoint = DOMUtil.UTIL.getAttribute(providerElem, "endpoint-name"); connInfo.put("to-service", toSvc); connInfo.put("to-endpoint", toEndpoint); } catch(Exception e) { e.printStackTrace(); String jbiExStr = null; String errMsg = mTranslator.getString( LocalStringKeys.DS_UNABLE_TO_GET_CONNECTIONS_INFO, saName); jbiExStr = buildFrmwkExMsg("getConnectionsInfo", e, errMsg); throw new DeploymentException(jbiExStr); } return connInfo; } /** * Activate Service Connections defined in the specified Service Assembly. * * @param saName The name of the Service Assembly. * @return a HashMap of result messages with the endpoint or interface * names as the keys. * @throws Exception if an unrecoverable error occurs. */ HashMap activateConnections(String saName) throws Exception { return activateConnections(saName, true); } /** * Activate Service Connections defined in the specified Service Assembly. * * @param saName The name of the Service Assembly. * @param xmlMsg When set to true, requests that error messages * returned in the HashMap be in XML management message format. When set to * false, error messages are in text format. * @return a HashMap of result messages with the endpoint or interface * names as the keys. * @throws Exception if an unrecoverable error occurs. */ public HashMap activateConnections(String saName, boolean xmlMsg) throws Exception { ConnectionManager connMgr = null; HashMap infoMsgMap = new HashMap(); Element connctnsElement = getConnectionsElement(saName); if(connctnsElement == null) { //There is no connections info. in //deployment descriptor. return null; } NodeList nl = DOMUtil.UTIL.getChildElements(connctnsElement, "connection"); if(nl.getLength() == 0) { //No connection elements. return return null; } String fromEndpoint = null; QName intrfcName = null; for(int i=0; i "%20") to handle odd cases like installation * directories containing a space. * * @param installJarURI - String containing URL to convert * @return - a URL fixing spaces contained within. * @throws java.net.MalformedURLException if an error occurs */ private URL convertToProperURL(String installJarURI) throws java.net.MalformedURLException { // Encode the # installJarURI = installJarURI.replaceAll("#", "%23"); // fix problems commonly occuring with 'file:' URLs on Windows if (installJarURI.startsWith("file://")) { return new File(installJarURI.substring(7)).toURL(); } if (installJarURI.startsWith("file:" + File.separator)) { return new File(installJarURI.substring(5)).toURL(); } // next case: Windows only, skip over the / if (installJarURI.startsWith("file:/")) { return new File(installJarURI.substring(6)).toURL(); } if (installJarURI.startsWith("file:")) { return new File(installJarURI.substring(5)).toURL(); } // last ditch effort to handle URLs with non-encoded spaces try { return new java.net.URI(installJarURI.replaceAll(" ", "%20")).toURL(); } catch (java.net.URISyntaxException e) { throw new java.net.MalformedURLException(e.getMessage()); } } /** * @return the ServuceUnitInfo of a specific SU from the ServiceUnitInfoList */ private ServiceUnitInfo findDeploymentUnitInfo(List suInfoList, String suName) { ServiceUnitInfo suInfo = null; for (ServiceUnitInfo su : suInfoList) { if ( suName.equals(su.getName())) { suInfo = su; break; } } return suInfo; } public Iterator listServiceAssemblies(String compName) { ComponentInfo compInfo = getComponentQuery().getComponentInfo(compName); List serviceAssemblies = new ArrayList(); List suList = compInfo.getServiceUnitList(); for(ServiceUnitInfo su : suList) { if(!serviceAssemblies.contains(su.getServiceAssemblyName())) serviceAssemblies.add(su.getServiceAssemblyName()); } return serviceAssemblies.iterator(); } /** * Activate the Service Connections if SA state is Started, deactivate the * connections if state is Stopped or Shutdown. */ public void updateServiceAssemblyConnections(String compName) { String saName; Iterator saList = listServiceAssemblies(compName); mLogger.log(Level.FINE, "Updating Service Assembly Connections for component {0}", compName); while (saList.hasNext()) { saName = (String)saList.next(); updateSAState(saName); } } /** * Determines the appropriate state for a service assembly. This code is * necessary because the component autostart information may only be part * of the picture for a given SA (which can include multiple SUs, targeted * at multiple components). */ public String updateSAState(String saName) { String fwState; // state of SA based on framework state of SUs fwState = DeploymentServiceMBean.SHUTDOWN; try { ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName); List suList = saInfo.getServiceUnitList(); for ( ServiceUnitInfo su : suList ) { String suName = su.getName(); String compName = su.getTargetComponent(); ComponentInfo compInfo; List compSUs; ServiceUnitState suState = ServiceUnitState.SHUTDOWN; suState = getActualServiceUnitState(compName, suName); if (suState == ServiceUnitState.STARTED) { // all it takes is one SU in STARTED to flip the SA state fwState = DeploymentServiceMBean.STARTED; break; } else if (suState == ServiceUnitState.STOPPED) { // set the SA state to STOPPED, but keep looking for a started SU fwState = DeploymentServiceMBean.STOPPED; } } if ( fwState.equals(DeploymentServiceMBean.STARTED) ) { mLogger.log(Level.FINE, "Activating Connections for Service Assembly {0}", saName); activateConnections(saName); } else { mLogger.log(Level.FINE, "Deactivating Connections for Service Assembly {0}", saName); deactivateConnections(saName); } } catch (Exception ex) { mLogger.warning(mTranslator.getString( LocalStringKeys.DS_AUTOSTART_CONNECTION_PROCESSING_FAILED, saName, ex.toString())); } return fwState; } /*---------------------------------------------------------------------------------*\ * Private Helpers * \*---------------------------------------------------------------------------------*/ /** * @return true if the service assembly has zero service units * @param saName - name of the service assembly */ private boolean isServiceAssemblyEmpty(String saName) throws Exception { ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName, "domain"); return saInfo.getServiceUnitList().isEmpty(); } /** * @return the ServiceAssemblyInfo obtained from the Registry */ private ServiceAssemblyInfo getServiceAssemblyInfo(String saName, String target) throws Exception { ServiceAssemblyQuery saQuery = getRegistry().getServiceAssemblyQuery(target); ServiceAssemblyInfo saInfo = saQuery.getServiceAssemblyInfo(saName); if ( saInfo == null ) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_GET_SA_INFO_INVALID_SA_NAME, saName); throw new Exception(errMsg); } return saInfo; } /** * @return the ServiceAssemblyInfo obtained from the Registry */ private ServiceAssemblyInfo getServiceAssemblyInfo(String saName) throws Exception { ServiceAssemblyQuery saQuery = getRegistry().getServiceAssemblyQuery(); ServiceAssemblyInfo saInfo = saQuery.getServiceAssemblyInfo(saName); if ( saInfo == null ) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_GET_SA_INFO_INVALID_SA_NAME, saName); throw new Exception(errMsg); } return saInfo; } /** * Get the Connections Element from the Service Assembly Deployment descriptor */ public Element getConnectionsElement(String saName) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); String saDescriptor = getRegistry().getGenericQuery().getServiceAssemblyDeploymentDescriptor(saName); org.xml.sax.InputSource ipSrc= new org.xml.sax.InputSource(new StringReader(saDescriptor)); Document doc = db.parse(ipSrc); Element saElem = DOMUtil.UTIL.getElement(doc, "service-assembly"); return DOMUtil.UTIL.getElement(saElem, "connections"); } /** * Get the link-type for the Endpoint from the Service Units in the Service Assembly. * The DOM processing should be replaced by using JAXB. * * @param fromEndpoint - the connection consumer service endpoint * @param saName - the service assembly name */ public Link getLinkType(String fromEndpoint, String saName) throws Exception { Link linkType = null; try { ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName, "domain"); List suList = saInfo.getServiceUnitList(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); for ( ServiceUnitInfo su : suList ) { String suDescriptor = su.getFilePath() + File.separator + "META-INF" + File.separator + "jbi.xml"; File jbiXmlFile = new File(suDescriptor); if(jbiXmlFile.exists()) { Document doc = db.parse(jbiXmlFile); Element servicesElem = DOMUtil.UTIL.getElement(doc, "services"); Element consumesElem = DOMUtil.UTIL.getElement(servicesElem, "consumes"); if(consumesElem == null) { return null; } String endpointName = DOMUtil.UTIL.getAttribute(consumesElem, "endpoint-name"); if(endpointName.equalsIgnoreCase(fromEndpoint)) { String linkTypeStr = DOMUtil.UTIL.getAttribute(consumesElem, "link-type"); if(linkTypeStr.equalsIgnoreCase("HARD")) linkType = Link.HARD; if(linkTypeStr.equalsIgnoreCase("STANDARD")) linkType = Link.STANDARD; if(linkTypeStr.equalsIgnoreCase("SOFT")) linkType = Link.SOFT; break; } } } } catch(DeploymentException de) { throw de; } catch(Exception e) { String errMsg = mTranslator.getString( LocalStringKeys.DS_UNABLE_TO_GET_LINK_TYPE_FROM_SU_DESCRIPTOR, saName); String jbiTaskStr = buildFrmwkExMsg("getLinkType", e, errMsg); throw new DeploymentException(jbiTaskStr); } return linkType; } /** * Get the ObjectName of the ComponentLifeCycleMBean on the instance */ private ObjectName getComponentLifeCycleMBeanName(String componentName) { MBeanNames mbnNames = sMContext.getMBeanNames(); ObjectName compLCMBean = null; ComponentType compType = getComponentType(componentName); if ( ComponentType.BINDING == compType ) { compLCMBean = mbnNames.getBindingMBeanName(componentName, MBeanNames.CONTROL_TYPE_LIFECYCLE); } else { compLCMBean = mbnNames.getEngineMBeanName(componentName, MBeanNames.CONTROL_TYPE_LIFECYCLE); } return compLCMBean; } /** * @return the ComponentType of the component. If the component is not installed * a null value is returned */ private ComponentType getComponentType(String componentName) { ComponentType compType = null; ComponentInfo compInfo = getComponentQuery().getComponentInfo(componentName); if ( compInfo != null ) { compType = compInfo.getComponentType(); } return compType; } /** * Stop a service assembly, this operation is called by the pblic stop() operation * as well as the public shutDown() operation. * * @param serviceAssemblyName - target service assembly name * @param isStarted - flag indicating if the service assembly is in the started state. * If the service assembly is in the started state, the service connections need to * be deactivated. */ private String stopServiceAssembly(String serviceAssemblyName, boolean isStarted) throws Exception { HashMap infoMsgElems = null; if(isStarted) { infoMsgElems = deactivateConnections(serviceAssemblyName); } String stateChangeRslt = stopShutDownServiceAssembly("stop", serviceAssemblyName, false); String jbiTaskStr = appendMsgsToTaskRslt(stateChangeRslt, infoMsgElems, "WARNING"); return jbiTaskStr; } /** * @return the DeployerMBean instance for a component */ private DeployerMBean getComponentDeployerInstance(String compName) { return sMContext.getEnvironmentContext().getComponentManager().getDeployerInstance(compName); } /** * Return true if the component-task-results indicate partial success. *
      *
    • If all component-task-results have task-result=SUCCESS -> deployment completely successful
    • *
    • If one or more ( but not all ) component-task-results have task-result=SUCCESS -> deployment partiallly successful
    • *
    * * @param cmpTaskRslts - list of component-task-result elements * @return true if the component-task-results indicate partial success */ private boolean isPartialSuccess(List cmpTaskRslts) { int successCount = 0; int numComponentResults = cmpTaskRslts.size(); for ( Element cmpResult : cmpTaskRslts) { Element taskResult = DOMUtil.UTIL.getElement(cmpResult, "task-result"); String taskResultStr = DOMUtil.UTIL.getTextData(taskResult); if ( "SUCCESS".equalsIgnoreCase(taskResultStr) ) { successCount++; } } return ( (successCount > 0) && (successCount != numComponentResults) ); } /** * Checks the exception message for the component result xml. if found, * the message is converted to dom tree and returned. If the exception * message is a plain text, the whole exception is converted as a * dom tree of component result xml fragment * @param compName jbi component name * @param taskId task id * @param ex exception to convert to xml fragment * @return dom tree with component-task-result as its root element. */ private Element getComponentResultXmlFragment(String compName, String taskId, Exception ex) { String exMessage = ex.getMessage(); Element elem = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(exMessage))); elem = DOMUtil.UTIL.getElement(doc, "component-task-result"); } catch (Exception e) { elem = buildComponentExMsg(taskId, compName, ex); } return elem; } /** * This method is used to disable statistics collection in * deployment service */ public void disableStatistics() { mStatisticsEnabled = false; } /** * This method is used to enable statistics collection in * deployment service */ public void enableStatistics() { mStatisticsEnabled = true; } /** * This method is used to enable statistics collection in * deployment service */ public boolean isStatisticsEnabled() { return mStatisticsEnabled; } /** * This method is used to update SA statistics for the given SA * @param saName sa name * @param operation operation name * @param beginTime time when the operation was begun * @param endTime time when the operation was finished * @param suTimes map of su names to time taken for su operation * */ private void updateStatistics( String saName, String operationName, Date beginTime, Date endTime, Map suTimes) { if (!mStatisticsEnabled) { return; } try { if (!mServiceAssemblyStats.containsKey(saName)) { mServiceAssemblyStats.put(saName, createNewSAStatsObject(saName)); } ServiceAssemblyStatistics saStats = mServiceAssemblyStats.get(saName); if (saStats != null) { if (operationName.equals(START)) { mLogger.log(Level.FINER, "Updating startup statistics for service assembly {0}", saName); saStats.updateStartupStatistics(beginTime, endTime, suTimes); } else if (operationName.equals(STOP)) { mLogger.log(Level.FINER, "Updating stop statistics for service assembly {0}", saName); saStats.updateStopStatistics(beginTime, endTime, suTimes); } else if (operationName.equals(SHUTDOWN)) { mLogger.log(Level.FINER, "Updating shutdown statistics for service assembly {0}", saName); saStats.updateShutdownStatistics(beginTime, endTime, suTimes); } } } catch (Exception ex) { //we catch all the exceptions here because we do not want a failure in statistics //collection to affect the normal runtime processing String message = mTranslator.getString( LocalStringKeys.DS_ERROR_IN_COLLECTING_STATISTICS_FOR_SA, new Object[]{saName}); mLogger.warning(message); String exceptionMsg = ex.getMessage(); if (exceptionMsg != null) { mLogger.warning(exceptionMsg); } } } /** * This method is used to create a new ServiceAssembly statistics * object * @param saName the service assembly name * @return ServiceAssemblyStatistics SA stats object */ private ServiceAssemblyStatistics createNewSAStatsObject(String saName) { mLogger.log(Level.FINER, "Creating a new statistics object for service assembly {0}", saName); ServiceAssemblyInfo saInfo; String instanceName; ServiceAssemblyStatistics saStats = null; try { saInfo = getServiceAssemblyInfo(saName); instanceName = mEnv.getPlatformContext().getInstanceName(); saStats = new ServiceAssemblyStatistics(saName, instanceName); List suInfoList = saInfo.getServiceUnitList(); Map suList = new HashMap(); for (ServiceUnitInfo suInfo: suInfoList ) { ServiceAssemblyStatistics.ServiceUnitStatistics suStat = saStats.new ServiceUnitStatistics(suInfo.getName()); //todo get a list of endpoint names suStat.setEndpointsList(new ArrayList()); suList.put(suInfo.getName(), suStat); } saStats.setServiceUnitList(suList); } catch (Exception ex) { //getServiceAssemblyInfo throws Exception mLogger.warning(MessageHelper.getMsgString(ex)); return saStats; } return saStats; } /** * This method is used to get statistics for the given SA * @param saName the servie assembly name * @return ServiceAssemblyStatistics sa Stats * @throws RuntimeException is statistics for this SA are not available */ public ServiceAssemblyStatistics getServiceAssemblyStatistics(String saName) throws RuntimeException { mLogger.log(Level.FINER, "Getting statistics for service assembly {0}", saName); ServiceAssemblyStatistics saStats = mServiceAssemblyStats.get(saName); if (saStats == null) { String message = mTranslator.getString( LocalStringKeys.DS_NO_STATS_FOR_SA, new Object[] { saName} ); mLogger.warning(message); throw new RuntimeException(message); } return saStats; } /** * This method is used to remove the statistics object of the given SA. * This object is removed after a SA is undeployed. * @param saName the service assembly name */ public void removeStatsObject(String saName) { mLogger.log(Level.FINER, "Removing statistics object for service assembly {0}", saName); if (mServiceAssemblyStats != null) { mServiceAssemblyStats.remove(saName); } } /** * Bring all Service Assemblies to their desired states. This is done * only during startup of the runtime, after all components have been * brought to their desired states. Any failures that occur here are * logged. * * Note: There is a requirement in the JSR208 specification that all * Service Units must be initialized during startup of the runtime to * eliminate the need for components to persist SU information. This * means that for any SUs whose containing SA has a desired state of * "Shutdown", the SU must be shut down after it is initialized. Here * is the text from the JSR208 specification: * * * JBI implementations MUST retain the running state of all service unit * deployments, such that the schemaorg_apache_xmlbeans.system can be restarted from a shutdown or * crash, and all deployments will be restored to their previous running * state. During component restart, the implementation MUST perform the * following to restore a service unit to its previous state: *
      *
    • * Started. The implementation MUST call init(), followed by start(). *
    • *
    • * Stopped. The implementation MUST call init() to restore a service * unit to the stopped state. *
    • *
    • * Shutdown. The implementation MUST call init() followed by shutDown() * to restore a service unit to the shutdown state. *
    • * In all cases of state restoration, the implementation MUST call init() * for all service units in the group being restored before any other life * cycle methods for service units in the group are called *
      * * In support of the above requirement, this method first initializes ALL * deployed Service Assemblies. After that, all deployed SAs are brought to * their desired states, either "Shutdown", "Stopped", or "Started". */ public void startAllServiceAssemblies() { // First get a list of all deployed service assemblies ServiceAssemblyQuery saQuery = null; List saNamesList; try { saQuery = getRegistry().getServiceAssemblyQuery(); saNamesList = saQuery.getServiceAssemblies(); } catch (Exception e) { String errMsg = mTranslator.getString( LocalStringKeys.DS_UNABLE_TO_FIND_DEPLOYED_SERVICE_ASSEMBLY_NAMES); mLogger.log(Level.WARNING, errMsg, e); saNamesList = new ArrayList(); } // Now get a list of deployed service assemblies that need to be // shut down or started. Note that service assemblies with a desired // state of "stopped" will be handled by initializing them. The list // is a map of service assembly names to their desired states. We have // to capture their states here because the init processing updates // their states. HashMap saList = new HashMap(); for ( String name : saNamesList ) { ServiceAssemblyInfo saInfo = saQuery.getServiceAssemblyInfo(name); if ( saInfo.getStatus() != ServiceAssemblyState.STOPPED ) { saList.put(name, saInfo.getStatus()); mLogger.log(Level.FINE, "Service Assembly {0} with state {1} added to start/shutdown list", new Object[]{name, saInfo.getStatus()}); } } int successCount = 0; int failureCount = 0; // Now, initialize all deployed service assemblies mLogger.log(Level.FINE, "Initializing {0} Service Assemblies", saNamesList.size()); for ( String name : saNamesList ) { ServiceAssemblyInfo info = saQuery.getServiceAssemblyInfo(name); try { mLogger.log(Level.FINE, "Initializing Service Assembly {0}", name); initServiceAssembly(name, true); } catch ( Exception e ) { // increment failure count, remove this SA from the list // to be shutdown / started, and log the failure ++failureCount; saList.remove(name); mLogger.warning(MessageHelper.getMsgString(e)); } } // Finally, bring all service assemblies in the start/shutdown list // to the appropriate states Iterator> sa = saList.entrySet().iterator(); while ( sa.hasNext() ) { Map.Entry entry = (Map.Entry) sa.next(); String saName = entry.getKey(); ServiceAssemblyState saState = entry.getValue(); try { if ( saState == ServiceAssemblyState.SHUTDOWN ) { mLogger.log(Level.FINER, "Shutting down Service Assembly {0}", saName); shutDown(saName); } else if ( saState == ServiceAssemblyState.STARTED ) { mLogger.log(Level.FINER, "Activating Connections for Service Assembly {0}", saName); activateConnections(saName); mLogger.log(Level.FINER, "Starting Service Assembly {0}", saName); startServiceAssembly(saName); } ++successCount; } catch ( Exception e ) { // convert exception message to text and log it ++failureCount; mLogger.warning(MessageHelper.getMsgString(e)); } } if ( 0 < successCount ) { mLogger.info(mTranslator.getString( LocalStringKeys.DS_SA_STARTUP_SUCCESS, successCount)); } if ( 0 < failureCount ) { mLogger.warning(mTranslator.getString( LocalStringKeys.DS_SA_STARTUP_ERRORS, failureCount)); } } /** * Initialize a Service Assembly. All the Service Units of this Service * Assembly that satisfy the following criteria are initialized: *
    • *
        the service unit is deployed
      *
        the service unit is not already initialized
      *
        the target component is installed
      *
        the target component is not in the "Shutdown" state
      *
    • *
      * This operation first filters out the Service Units to be initialized. * * @param saName name of service assembly to be targeted */ String initServiceAssembly(String saName) throws Exception { return initServiceAssembly(saName, false); } /** * Initialize a Service Assembly. All the Service Units of this Service * Assembly that satisfy the following criteria are initialized: *
    • *
        the service unit is deployed
      *
        the service unit is not already initialized
      *
        the target component is installed
      *
        the target component is not in the "Shutdown" state
      *
    • *
      * This operation first filters out the Service Units to be initialized. * * @param saName name of service assembly to be initialized * @param startup - set to true to ignore errors due to non-started * components. This is used when called from startAllServiceAssemblies() * during schemaorg_apache_xmlbeans.system startup. */ String initServiceAssembly(String saName, boolean startup) throws Exception { String saLifecycleMthdName = "init"; List cmpTaskRslts = new ArrayList(); boolean saStateChangeRslt = true; try { int operationCount = 0; int successCount = 0; ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName); List suList = saInfo.getServiceUnitList(); List susToInitialize = new ArrayList(); if ( isServiceAssemblyEmpty(saName) ) { getRegistry().getUpdater().setServiceAssemblyState( ServiceAssemblyState.STOPPED, saName); return buildResponse(cmpTaskRslts, saStateChangeRslt, saLifecycleMthdName, saName); } for ( ServiceUnitInfo su : suList ) { String suName = su.getName(); String compName = su.getTargetComponent(); try { if ( !isDeployedServiceUnit(compName, suName) ) { mLogger.log(Level.FINE, "Service unit {0} is not deployed to component {1} : ignoring init request", new Object[]{suName, compName}); continue; } ComponentState cmpState = getComponentState(compName); if (cmpState == ComponentState.UNKNOWN) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_NOT_INSTALLED, suName, compName); mLogger.warning(errMsg); } else if (cmpState == ComponentState.SHUTDOWN) { if ( startup ) { continue; } // this counts as a failed operation, increment counter ++operationCount; String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE, suName, compName); mLogger.warning(errMsg); } } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, saLifecycleMthdName, e); cmpTaskRslts.add(elem); // Stop processing and try to change the state // of the next SU in the SA. continue; } ServiceUnitState currSuState = getActualServiceUnitState(compName, suName); if ( ServiceUnitState.SHUTDOWN == currSuState ) { susToInitialize.add(su); } } // Now initialize all the service units that need to be initialized. for ( ServiceUnitInfo su : susToInitialize ) { String suName = su.getName(); String compName = su.getTargetComponent(); try { // -- increment op counter for each su life cycle operation ++operationCount; DeployerMBean deployer = getComponentDeployerInstance(compName); deployer.init(su.getName(), su.getFilePath()); ++successCount; } catch (Exception e) { Element elem = getComponentResultXmlFragment(compName, saLifecycleMthdName, e); cmpTaskRslts.add(elem); } } // Init is successful if at least one operation succeeds if ( operationCount > 0 && successCount == 0 ) { saStateChangeRslt = false; } } catch (Exception e) { String errMsg = mTranslator.getString( LocalStringKeys.DS_CANNOT_CHANGE_SERVICE_ASSEMBLY_STATE, saName); String jbiTaskStr = buildFrmwkExMsg(saLifecycleMthdName, e, errMsg); throw new Exception(jbiTaskStr); } String resp = buildResponse(cmpTaskRslts, saStateChangeRslt, saLifecycleMthdName, saName); if (!saStateChangeRslt) { // operation failed completely, throw an exception with result text throw new Exception(resp); } return resp; } }




    © 2015 - 2024 Weber Informatics LLC | Privacy Policy