servicemix-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From gno...@apache.org
Subject svn commit: r382984 [2/4] - in /incubator/servicemix/trunk/servicemix-core/src: main/java/org/apache/servicemix/jbi/container/ main/java/org/apache/servicemix/jbi/framework/ main/java/org/apache/servicemix/jbi/loaders/ main/java/org/apache/servicemix/j...
Date Sat, 04 Mar 2006 00:31:55 GMT
Modified: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/DeploymentService.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/DeploymentService.java?rev=382984&r1=382983&r2=382984&view=diff
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/DeploymentService.java (original)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/DeploymentService.java Fri Mar  3 16:31:49 2006
@@ -14,10 +14,12 @@
  * limitations under the License.
  */
 package org.apache.servicemix.jbi.framework;
+
 import java.io.File;
 import java.io.IOException;
-import java.util.HashSet;
-import java.util.Set;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.List;
 
 import javax.jbi.JBIException;
 import javax.jbi.component.Component;
@@ -27,25 +29,28 @@
 import javax.management.JMException;
 import javax.management.MBeanAttributeInfo;
 import javax.management.MBeanOperationInfo;
-import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.servicemix.jbi.container.EnvironmentContext;
 import org.apache.servicemix.jbi.container.JBIContainer;
-import org.apache.servicemix.jbi.deployment.Connection;
-import org.apache.servicemix.jbi.deployment.Consumer;
 import org.apache.servicemix.jbi.deployment.Descriptor;
-import org.apache.servicemix.jbi.deployment.Provider;
 import org.apache.servicemix.jbi.deployment.ServiceAssembly;
 import org.apache.servicemix.jbi.deployment.ServiceUnit;
-import org.apache.servicemix.jbi.deployment.Target;
 import org.apache.servicemix.jbi.management.AttributeInfoHelper;
 import org.apache.servicemix.jbi.management.BaseSystemService;
 import org.apache.servicemix.jbi.management.OperationInfoHelper;
 import org.apache.servicemix.jbi.management.ParameterHelper;
-import org.apache.servicemix.jbi.servicedesc.InternalEndpoint;
+import org.apache.servicemix.jbi.util.DOMUtil;
 import org.apache.servicemix.jbi.util.FileUtil;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
 
 /**
  * The deployment service MBean allows administrative tools to manage service assembly deployments.
@@ -56,7 +61,11 @@
     
     private static final Log log = LogFactory.getLog(DeploymentService.class);
     private EnvironmentContext environmentContext;
+    private Registry registry;
     
+    //
+    // ServiceMix service implementation
+    //
 
     /**
      * Initialize the Service
@@ -66,8 +75,10 @@
      * @throws DeploymentException
      */
     public void init(JBIContainer container) throws JBIException {
-        super.init(container);
         this.environmentContext = container.getEnvironmentContext();
+        this.registry = container.getRegistry();
+        super.init(container);
+        buildState();
     }
     
     protected Class getServiceMBean() {
@@ -75,11 +86,70 @@
     }
 
     public void start() throws javax.jbi.JBIException {
-        buildState();
         super.start();
+        String[] sas = registry.getDeployedServiceAssemblies();
+        for (int i = 0; i < sas.length; i++) {
+            try {
+                ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(sas[i]);
+                sa.restore();
+            } catch (Exception e) {
+                log.error("Unable to restore state for service assembly " + sas[i], e);
+            }
+        }
     }
     
     /**
+     * Get an array of MBeanAttributeInfo
+     * 
+     * @return array of AttributeInfos
+     * @throws JMException
+     */
+    public MBeanAttributeInfo[] getAttributeInfos() throws JMException {
+        AttributeInfoHelper helper = new AttributeInfoHelper();
+        helper.addAttribute(getObjectToManage(), "deployedServiceAssemblies", "list of deployed SAs");
+        return AttributeInfoHelper.join(super.getAttributeInfos(), helper.getAttributeInfos());
+    }
+
+    /**
+     * Get an array of MBeanOperationInfo
+     * 
+     * @return array of OperationInfos
+     * @throws JMException
+     */
+    public MBeanOperationInfo[] getOperationInfos() throws JMException {
+        OperationInfoHelper helper = new OperationInfoHelper();
+        ParameterHelper ph = helper.addOperation(getObjectToManage(), "deploy", 1, "deploy An SA");
+        ph.setDescription(0, "saZipURL", "location of SA zip file");
+        ph = helper.addOperation(getObjectToManage(), "undeploy", 1, "undeploy An SA");
+        ph.setDescription(0, "saName", "SA name");
+        ph = helper.addOperation(getObjectToManage(), "getDeployedServiceUnitList", 1,
+                "list of SU's currently deployed");
+        ph.setDescription(0, "componentName", "Component name");
+        ph = helper.addOperation(getObjectToManage(), "getServiceAssemblyDescriptor", 1, "Get descriptor for a SA");
+        ph.setDescription(0, "saName", "SA name");
+        ph = helper.addOperation(getObjectToManage(), "getDeployedServiceAssembliesForComponent", 1,
+                "list of SA's for a Component");
+        ph.setDescription(0, "componentName", "Component name");
+        ph = helper.addOperation(getObjectToManage(), "getComponentsForDeployedServiceAssembly", 1,
+                "list of Components  for a SA");
+        ph.setDescription(0, "saName", "SA name");
+        ph = helper.addOperation(getObjectToManage(), "isDeployedServiceUnit", 2, "is SU deployed at a Component ?");
+        ph.setDescription(0, "componentName", "Component name");
+        ph.setDescription(1, "suName", "SU name");
+        ph = helper
+                .addOperation(getObjectToManage(), "canDeployToComponent", 1, "Can a SU be deployed to a Component?");
+        ph.setDescription(0, "componentName", "Component name");
+        ph = helper.addOperation(getObjectToManage(), "start", 1, "start an SA");
+        ph.setDescription(0, "saName", "SA name");
+        ph = helper.addOperation(getObjectToManage(), "stop", 1, "stop an SA");
+        ph.setDescription(0, "saName", "SA name");
+        ph = helper.addOperation(getObjectToManage(), "shutDown", 1, "shutDown an SA");
+        ph.setDescription(0, "saName", "SA name");
+        ph = helper.addOperation(getObjectToManage(), "getState", 1, "Running state of an SA");
+        ph.setDescription(0, "saName", "SA name");
+        return OperationInfoHelper.join(super.getOperationInfos(), helper.getOperationInfos());
+    }
+    /**
      * Get the description
      * 
      * @return description
@@ -88,69 +158,53 @@
         return "Allows admin tools to manage service deployments";
     }
 
+    //
+    // DeploymentServiceMBean implementation
+    //
+
     /**
      * Deploys the given SA to the JBI environment.
      * 
      * @param saZipURL String containing the location of the Service Assembly zip file.
-     * @return Result/Status of the SA deployment.
-     * @throws Exception if complete deployment fails.
+     * @return Result/Status of the SA deployment in xml format.
+     * @throws Exception in xml format if complete deployment fails.
      */
     public String deploy(String saZipURL) throws Exception {
         try {
-            String result = null;
-            File tmpDir = AutoDeploymentService.unpackLocation(environmentContext.getTmpDir(), saZipURL);
-            Descriptor root = AutoDeploymentService.buildDescriptor(tmpDir);
-            ServiceAssembly sa = root.getServiceAssembly();
-            if (sa != null) {
-                result = deploy(tmpDir, sa);
+            if (saZipURL == null) {
+                throw ManagementSupport.failure("deploy", "saZipURL must not be null");
             }
-            else {
-                throw new DeploymentException("Not an assembly: " + saZipURL);
+            File tmpDir = null;
+            try {
+                tmpDir = AutoDeploymentService.unpackLocation(environmentContext.getTmpDir(), saZipURL);
+            } catch (Exception e) {
+                throw ManagementSupport.failure("deploy", "Unable to unpack archive: " + saZipURL, e);
+            }
+            // unpackLocation returns null if no jbi descriptor is found
+            if (tmpDir == null) {
+                throw ManagementSupport.failure("deploy", "Unable to find jbi descriptor: " + saZipURL);
+            }
+            Descriptor root = null;
+            try {
+                root = AutoDeploymentService.buildDescriptor(tmpDir);
+            } catch (Exception e) {
+                throw ManagementSupport.failure("deploy", "Unable to build jbi descriptor: " + saZipURL, e);
             }
-            return result;
+            if (root == null) {
+                throw ManagementSupport.failure("deploy", "Unable to find jbi descriptor: " + saZipURL);
+            }
+            ServiceAssembly sa = root.getServiceAssembly();
+            if (sa == null) {
+                throw ManagementSupport.failure("deploy", "JBI descriptor is not an assembly descriptor: " + saZipURL);
+            }
+            return deployServiceAssembly(tmpDir, sa);
         } catch (Exception e) {
-            log.info("Unable to deploy assembly", e);
+            log.error("Error deploying service assembly", e);
             throw e;
         }
     }
 
     /**
-     * Deploy an SA
-     * 
-     * @param tmpDir
-     * @param sa
-     * @return result/status of the deployment
-     * @throws Exception
-     */
-    protected String deploy(File tmpDir, ServiceAssembly sa) throws Exception {
-        String result = "";
-        String assemblyName = sa.getIdentification().getName();
-        File oldSaDirectory = environmentContext.getSARootDirectory(assemblyName);
-        FileUtil.deleteFile(oldSaDirectory);
-        File saDirectory = environmentContext.createSARootDirectory(assemblyName);
-        log.info(assemblyName + " Moving " + tmpDir.getAbsolutePath() + " to " + saDirectory.getAbsolutePath());
-        
-        if (tmpDir.renameTo(saDirectory)) {
-            // move the assembly to a well-named holding area
-            ServiceUnit[] sus = sa.getServiceUnits();
-            if (sus != null) {
-                for (int i = 0;i < sus.length;i++) {
-                    if (i > 0) {
-                        result += " ; ";
-                    }
-                    result += deployServiceUnit(saDirectory, sus[i]);
-                }
-            }
-            buildConnections(sa);
-            container.getRegistry().registerServiceAssembly(sa);
-        }
-        else {
-            log.error("Failed to rename " + tmpDir + " TO " + saDirectory);
-        }
-        return result;
-    }
-
-    /**
      * Undeploys the given SA from the JBI environment.
      * 
      * @param saName name of the SA that has to be undeployed.
@@ -158,16 +212,26 @@
      * @throws Exception if compelete undeployment fails.
      */
     public String undeploy(String saName) throws Exception {
+        if (saName == null) {
+            throw ManagementSupport.failure("undeploy", "SA name must not be null");
+        }
+        ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(saName);
+        if (sa == null) {
+            throw ManagementSupport.failure("undeploy", "SA has not been deployed: " + saName);
+        }
+        String state = sa.getCurrentState();
+        if (!DeploymentServiceMBean.SHUTDOWN.equals(state)) {
+            throw ManagementSupport.failure("undeploy", "SA must be shut down: " + saName);
+        }
         try {
             String result = null;
-            ServiceAssembly sa = container.getRegistry().getServiceAssembly(saName);
             if (sa != null) {
-                container.getRegistry().unregisterServiceAssembly(sa);
-                String assemblyName = sa.getIdentification().getName();
+                String assemblyName = sa.getName();
+                registry.unregisterServiceAssembly(assemblyName);
                 File saDirectory = environmentContext.getSARootDirectory(assemblyName);
-                ServiceUnit[] sus = sa.getServiceUnits();
+                ServiceUnitLifeCycle[] sus = sa.getDeployedSUs();
                 if (sus != null) {
-                    for (int i = 0;i < sus.length;i++) {
+                    for (int i = 0;i < sus.length; i++) {
                         undeployServiceUnit(sus[i]);
                     }
                 }
@@ -188,7 +252,12 @@
      */
     public String[] getDeployedServiceUnitList(String componentName) throws Exception {
         try {
-            return container.getRegistry().getSADeployedServiceUnitList(componentName);
+            ServiceUnitLifeCycle[] sus = registry.getDeployedServiceUnits(componentName);
+            String[] names = new String[sus.length];
+            for (int i = 0; i < names.length; i++) {
+                names[i] = sus[i].getName();
+            }
+            return names;
         } catch (Exception e) {
             log.info("Unable to get deployed service unit list", e);
             throw e;
@@ -202,7 +271,7 @@
      */
     public String[] getDeployedServiceAssemblies() throws Exception {
         try {
-            return container.getRegistry().getDeployedServiceAssemblies();
+            return registry.getDeployedServiceAssemblies();
         } catch (Exception e) {
             log.info("Unable to get deployed service assemblies", e);
             throw e;
@@ -216,26 +285,15 @@
      * @return descriptor of the Service Assembly.
      */
     public String getServiceAssemblyDescriptor(String saName) throws Exception {
-        try {
-            ServiceAssembly sa =  container.getRegistry().getServiceAssembly(saName);
-            return sa != null ? sa.getIdentification().getDescription() : "";
-        } catch (Exception e) {
-            log.info("Error in getServiceAssemblyDescriptor", e);
-            throw e;
+        ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(saName);
+        if (sa != null) {
+            return sa.getDescriptor();
+        } else {
+            return null;
         }
     }
 
     /**
-     * See if an Sa is already deployed
-     * 
-     * @param saName
-     * @return true if already deployed
-     */
-    protected boolean isSaDeployed(String saName) {
-        return container.getRegistry().getServiceAssembly(saName) != null;
-    }
-
-    /**
      * Returns a list of Service Assemblies that contain SUs for the given component.
      * 
      * @param componentName name of the component.
@@ -244,7 +302,7 @@
      */
     public String[] getDeployedServiceAssembliesForComponent(String componentName) throws Exception {
         try {
-            return container.getRegistry().getDeployedServiceAssembliesForComponent(componentName);
+            return registry.getDeployedServiceAssembliesForComponent(componentName);
         } catch (Exception e) {
             log.info("Error in getDeployedServiceAssembliesForComponent", e);
             throw e;
@@ -260,7 +318,7 @@
      */
     public String[] getComponentsForDeployedServiceAssembly(String saName) throws Exception {
         try {
-            return container.getRegistry().getComponentsForDeployedServiceAssembly(saName);
+            return registry.getComponentsForDeployedServiceAssembly(saName);
         } catch (Exception e) {
             log.info("Error in getComponentsForDeployedServiceAssembly", e);
             throw e;
@@ -277,7 +335,7 @@
      */
     public boolean isDeployedServiceUnit(String componentName, String suName) throws Exception {
         try {
-            return container.getRegistry().isSADeployedServiceUnit(componentName, suName);
+            return registry.isSADeployedServiceUnit(componentName, suName);
         } catch (Exception e) {
             log.info("Error in isSADeployedServiceUnit", e);
             throw e;
@@ -291,9 +349,8 @@
      * @return boolean value indicating whether the SU can be deployed.
      */
     public boolean canDeployToComponent(String componentName) {
-        boolean result = false;
-        result = container.getComponent(componentName) != null;
-        return result;
+        LocalComponentConnector lcc = container.getLocalComponentConnector(componentName);
+        return lcc != null && lcc.getComponentMBean().isStarted() && lcc.getServiceUnitManager() != null;
     }
 
     /**
@@ -305,7 +362,8 @@
      */
     public String start(String serviceAssemblyName) throws Exception {
         try {
-            return container.getRegistry().startServiceAssembly(serviceAssemblyName);
+            ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(serviceAssemblyName);
+            return sa.start(true);
         } catch (Exception e) {
             log.info("Error in start", e);
             throw e;
@@ -323,7 +381,8 @@
      */
     public String stop(String serviceAssemblyName) throws Exception {
         try {
-            return container.getRegistry().stopServiceAssembly(serviceAssemblyName);
+            ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(serviceAssemblyName);
+            return sa.stop(true);
         } catch (Exception e) {
             log.info("Error in stop", e);
             throw e;
@@ -339,7 +398,8 @@
      */
     public String shutDown(String serviceAssemblyName) throws Exception {
         try {
-            return container.getRegistry().shutDownServiceAssembly(serviceAssemblyName);
+            ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(serviceAssemblyName);
+            return sa.shutDown(true);
         } catch (Exception e) {
             log.info("Error in shutDown", e);
             throw e;
@@ -355,95 +415,215 @@
      */
     public String getState(String serviceAssemblyName) throws Exception {
         try {
-            return container.getRegistry().getServiceAssemblyState(serviceAssemblyName);
+            ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(serviceAssemblyName);
+            return sa.getCurrentState();
         } catch (Exception e) {
             log.info("Error in getState", e);
             throw e;
         }
     }
 
-    protected Set getComponentNames(ServiceAssembly sa) {
-        Set names = null;
-        if (sa.getServiceUnits() != null && sa.getServiceUnits().length > 0) {
-        	names = new HashSet();
-        	for (int i = 0; i < sa.getServiceUnits().length; i++) {
-        		names.add(sa.getServiceUnits()[i].getTarget().getComponentName());
-        	}
-        }
-        return names;
-    }
-
-    protected String deployServiceUnit(File location, ServiceUnit su) throws DeploymentException {
-        String result = null;
-        String name = su.getIdentification().getName();
-        Target target = su.getTarget();
-        String componentName = target.getComponentName();
-        String artifact = target.getArtifactsZip();
-        try {
-            File targetDir = environmentContext.getServiceUnitDirectory(componentName, name);
-            // unpack the artifact
-            if (artifact != null) {
-                File artifactFile = new File(location, artifact);
-                log.debug("Artifact is [" + artifactFile.getAbsolutePath() + "]");
-                if (artifactFile.exists()) {
-                    log.info("deployServiceUnit: unpack archive " + artifactFile + " to " + targetDir);
-                    // FileUtil.moveFile(artifactFile, targetDir);
-                    FileUtil.unpackArchive(artifactFile, targetDir);
-                    // now get the component and give it a SA
+    /**
+     * See if an Sa is already deployed
+     * 
+     * @param serviceAssemblyName - name of the service assembly.
+     * @return true if already deployed
+     */
+    protected boolean isSaDeployed(String serviceAssemblyName) {
+        return registry.getServiceAssembly(serviceAssemblyName) != null;
+    }
+
+    /**
+     * Deploy an SA
+     * 
+     * @param tmpDir
+     * @param sa
+     * @return result/status of the deployment in xml format
+     * @throws Exception  in xml format
+     */
+    protected String deployServiceAssembly(File tmpDir, ServiceAssembly sa) throws Exception {
+        String assemblyName = sa.getIdentification().getName();
+        File oldSaDirectory = environmentContext.getSARootDirectory(assemblyName);
+        FileUtil.deleteFile(oldSaDirectory);
+        File saDirectory = environmentContext.createSARootDirectory(assemblyName);
+
+        // move the assembly to a well-named holding area
+        if (log.isDebugEnabled()) {
+            log.debug("Moving " + tmpDir.getAbsolutePath() + " to " + saDirectory.getAbsolutePath());
+        }
+        if (!tmpDir.renameTo(saDirectory)) {
+            throw ManagementSupport.failure("deploy", "Failed to rename " + tmpDir + " to " + saDirectory);
+        }
+        // Check all SUs requirements
+        ServiceUnit[] sus = sa.getServiceUnits();
+        if (sus != null) {
+            for (int i = 0; i < sus.length; i++) {
+                String suName = sus[i].getIdentification().getName();
+                String artifact = sus[i].getTarget().getArtifactsZip();
+                String componentName = sus[i].getTarget().getComponentName();
+                File artifactFile = new File(saDirectory, artifact);
+                if (!artifactFile.exists()) {
+                    throw ManagementSupport.failure("deploy", "Artifact " + artifact + " not found for service unit " + suName);
+                }
+                LocalComponentConnector lcc = container.getLocalComponentConnector(componentName);
+                if (lcc == null) {
+                    throw ManagementSupport.failure("deploy", "Target component " + componentName + " for service unit " + suName + " is not installed");
+                }
+                if (!lcc.getComponentMBean().isStarted()) {
+                    throw ManagementSupport.failure("deploy", "Target component " + componentName + " for service unit " + suName + " is not started");
                 }
-                else {
-                    throw new DeploymentException("artifact: " + artifact + "(" + artifactFile.getAbsolutePath()
-                            + ") doesn't exist");
-                }
-            }
-            Component component = container.getComponent(componentName);
-            if (component != null) {
-                ServiceUnitManager sum = component.getServiceUnitManager();
-                if (sum != null) {
-                    result = sum.deploy(name, targetDir.getAbsolutePath());
-                    //sum.init(name, targetDir.getAbsolutePath());
-                    // register active endpoints
+                if (lcc.getServiceUnitManager() == null) {
+                    throw ManagementSupport.failure("deploy", "Target component " + componentName + " for service unit " + suName + " does not accept deployments");
                 }
-                else {
+                // TODO: check duplicates here ?
+                if (isDeployedServiceUnit(componentName, suName)) {
+                    throw ManagementSupport.failure("deploy", "Service unit " + suName + " is already deployed on component " + componentName);
+                }
+            }
+        }
+        // Everything seems ok, so deploy all SUs
+        int nbSuccess = 0;
+        int nbFailures = 0;
+        List componentResults = new ArrayList();
+        List suKeys = new ArrayList();
+        if (sus != null) {
+            for (int i = 0; i < sus.length; i++) {
+                File targetDir = null;
+                String suName = sus[i].getIdentification().getName();
+                String artifact = sus[i].getTarget().getArtifactsZip();
+                String componentName = sus[i].getTarget().getComponentName();
+                // TODO: skip duplicates
+                // Unpack SU
+                try {
+                    File artifactFile = new File(saDirectory, artifact);
+                    targetDir = environmentContext.getServiceUnitDirectory(componentName, suName);
+                    if (log.isDebugEnabled()) {
+                        log.debug("Unpack service unit archive " + artifactFile + " to " + targetDir);
+                    }
+                    FileUtil.unpackArchive(artifactFile, targetDir);
+                } catch (IOException e) {
+                    nbFailures++;
+                    componentResults.add(ManagementSupport.createComponentFailure(
+                            "deploy", componentName,
+                            "Error unpacking service unit", e));
+                    continue;
+                }
+                // Deploy it
+                boolean success = false;
+                try {
+                    LocalComponentConnector lcc = container.getLocalComponentConnector(componentName);
+                    ServiceUnitManager sum = lcc.getServiceUnitManager();
+                    String resultMsg = sum.deploy(suName, targetDir.getAbsolutePath());
+                    success = getComponentTaskResult(resultMsg, componentName, componentResults, true);
+                    // TODO: need to register the SU somewhere to keep track of its state
+                } catch (Exception e) {
+                    // Delete SU deployment dir
                     FileUtil.deleteFile(targetDir);
-                    throw new DeploymentException("Component " + componentName + " doesn't have a ServiceUnitManager");
+                    getComponentTaskResult(e.getMessage(), componentName, componentResults, false);
+                }
+                if (success) {
+                    nbSuccess++;
+                    suKeys.add(registry.registerServiceUnit(sus[i], assemblyName));
+                } else {
+                    nbFailures++;
                 }
             }
-            else {
-                FileUtil.deleteFile(targetDir);
-                throw new DeploymentException("Component " + componentName + " doesn't exist");
+        }
+        // Total failure
+        if (nbSuccess == 0 && nbFailures > 0) {
+            // Delete SA deployment directory 
+            FileUtil.deleteFile(tmpDir);
+            throw ManagementSupport.failure("deploy", componentResults);
+        }
+        // Success
+        else {
+            // Register SA
+            String[] deployedSUs = (String[]) suKeys.toArray(new String[suKeys.size()]);
+            registry.registerServiceAssembly(sa, deployedSUs);
+            // Build result string
+            if (nbFailures > 0) {
+                return ManagementSupport.createWarningMessage("deploy", "Failed to deploy some service units", componentResults);
+            } else {
+                return ManagementSupport.createSuccessMessage("deploy", componentResults);
             }
         }
-        catch (IOException e) {
-            log.error("Could not deploy ServiceUnit: " + name + " to component " + componentName, e);
-            throw new DeploymentException(e);
-        }
-        log.info("Deployed ServiceUnit " + name + " to Component: " + componentName);
-        return result;
-    }
-
-    protected void undeployServiceUnit(ServiceUnit su) throws DeploymentException {
-        String name = su.getIdentification().getName();
-        Target target = su.getTarget();
-        String componentName = target.getComponentName();
-        try {
-            File targetDir = environmentContext.getServiceUnitDirectory(componentName, name);
-            // unpack the artifact
-            // now get the component and give it a SA
-            Component component = container.getComponent(componentName);
-            if (component != null) {
-                ServiceUnitManager sum = component.getServiceUnitManager();
-                if (sum != null) {
-                    sum.undeploy(name, targetDir.getAbsolutePath());
-                    FileUtil.deleteFile(targetDir);
+    }
+    
+    protected boolean getComponentTaskResult(String resultMsg, String component, List results, boolean success) {
+        Element result = null;
+        try {
+            Document doc = parse(resultMsg);
+            result = getElement(doc, "component-task-result");
+            Element e = getChildElement(result, "component-task-result-details");
+            e = getChildElement(e, "task-result-details");
+            e = getChildElement(e, "task-result");
+            String r = DOMUtil.getElementText(e);
+            if (!"SUCCESS".equals(r)) {
+                success = false;
+            }
+        } catch (Exception e) {
+            // The component did not throw an exception upon deployment,
+            // but the result string is not compliant, so issue a warning
+            // and consider this is a successfull deployment
+            try {
+                if (success) {
+                    result = ManagementSupport.createComponentFailure(
+                            "deploy", component,
+                            "Unable to parse result string", e);
+                } else {
+                    result = ManagementSupport.createComponentWarning(
+                            "deploy", component,
+                            "Unable to parse result string", e);
                 }
+            } catch (Exception e2) {
+                log.error(e2);
+                result = null;
             }
-            else {
+        }
+        if (result != null) {
+            results.add(result);
+        }
+        return success;
+    }
+    
+    protected Document parse(String result) throws ParserConfigurationException, SAXException, IOException {
+        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        factory.setNamespaceAware(true);
+        factory.setIgnoringElementContentWhitespace(true);
+        factory.setIgnoringComments(true);
+        DocumentBuilder builder = factory.newDocumentBuilder();
+        return builder.parse(new InputSource(new StringReader(result)));
+    }
+    
+    protected Element getElement(Document doc, String name) {
+        NodeList l = doc.getElementsByTagNameNS("http://java.sun.com/xml/ns/jbi/management-message", name);
+        Element e = (Element) l.item(0);
+        return e;
+    }
+    
+    protected Element getChildElement(Element element, String name) {
+        NodeList l = element.getElementsByTagNameNS("http://java.sun.com/xml/ns/jbi/management-message", name);
+        Element e = (Element) l.item(0);
+        return e;
+    }
+
+    protected void undeployServiceUnit(ServiceUnitLifeCycle su) throws DeploymentException {
+        String name = su.getName();
+        String componentName = su.getComponentName();
+        File targetDir = su.getServiceUnitRootPath();
+        registry.unregisterServiceUnit(su.getKey());
+        // unpack the artifact
+        // now get the component and give it a SA
+        Component component = container.getComponent(componentName);
+        if (component != null) {
+            ServiceUnitManager sum = component.getServiceUnitManager();
+            if (sum != null) {
+                sum.undeploy(name, targetDir.getAbsolutePath());
                 FileUtil.deleteFile(targetDir);
             }
         }
-        catch (IOException e) {
-            throw new DeploymentException(e);
+        else {
+            FileUtil.deleteFile(targetDir);
         }
         log.info("UnDeployed ServiceUnit " + name + " from Component: " + componentName);
     }
@@ -452,6 +632,7 @@
      * Find runnning state and things deployed before shutdown
      */
     protected void buildState() {
+        log.info("Restoring service assemblies");
         // walk through deployed SA's
         File top = environmentContext.getServiceAssembiliesDirectory();
         if (top != null && top.exists() && top.isDirectory()) {
@@ -461,16 +642,13 @@
                 for (int i = 0; i < files.length; i++) {
                     if (files[i].isDirectory()) {
                         String assemblyName = files[i].getName();
-                        log.info("initializing assembly " + assemblyName);
                         try {
                         	File assemblyDir = environmentContext.getSARootDirectory(assemblyName);
 	                        Descriptor root = AutoDeploymentService.buildDescriptor(assemblyDir);
 	                        if (root != null) {
 	                            ServiceAssembly sa = root.getServiceAssembly();
 	                            if (sa != null && sa.getIdentification() != null) {
-	                                container.getRegistry().registerServiceAssembly(sa);
-	                                buildConnections(sa);
-	                                container.getRegistry().restoreServiceAssembly(assemblyName);
+	                                registry.registerServiceAssembly(sa);
 	                            }
 	                        }
                         } catch(Exception e) {
@@ -482,151 +660,4 @@
         }
     }
 
-    protected void buildConnections(ServiceAssembly sa) throws JBIException {
-        if (sa != null) {
-            Connection[] connections = sa.getConnections().getConnections();
-            if (connections != null) {
-                for (int i = 0; i < connections.length; i++) {
-                    Connection connection = connections[i];
-                    Consumer consumer = connection.getConsumer();
-                    Provider provider = connection.getProvider();
-                    QName suName = consumer.getInterfaceName();
-                    if (suName != null) {
-                        LocalComponentConnector lcc = (LocalComponentConnector) container.getRegistry()
-                                .getComponentConnector(suName);
-                        if (lcc != null) {
-                            lcc.getActivationSpec().setDestinationEndpoint(provider.getEndpointName());
-                            lcc.getActivationSpec().setDestinationService(provider.getServiceName());
-                        }
-                        else {
-                            throw new DeploymentException("Unable to build connections, can't find consumer interface "
-                                    + suName);
-                        }
-                    }
-                    else {
-                        // We didn't have the interface so we will go after
-                        // the service name and endpoint
-                        InternalEndpoint endPoint = (InternalEndpoint) container.getRegistry().getEndpoint(
-                                consumer.getServiceName(), consumer.getEndpointName());
-                        if (endPoint != null) {
-                            LocalComponentConnector lcc = (LocalComponentConnector) container.getRegistry()
-                                    .getComponentConnector(endPoint.getComponentNameSpace());
-                            if (lcc != null) {
-                                lcc.getActivationSpec().setDestinationEndpoint(provider.getEndpointName());
-                                lcc.getActivationSpec().setDestinationService(provider.getServiceName());
-                            }
-                            else {
-                                throw new DeploymentException(
-                                        "Unable to build connections, can't find consumer based on component name space "
-                                                + endPoint.getComponentNameSpace());
-                            }
-                        }
-                        else {
-                            throw new DeploymentException(
-                                    "Unable to build connections, can't find consumer with servicename "
-                                            + consumer.getServiceName() + " and endpoint " + consumer.getEndpointName());
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    protected ServiceUnit getServiceUnit(String serviceUnitName, ServiceUnit[] sus) {
-        ServiceUnit result = null;
-        if (sus != null) {
-            for (int i = 0;i < sus.length;i++) {
-                if (sus[i].getIdentification().getName().equals(serviceUnitName)) {
-                    result = sus[i];
-                    break;
-                }
-            }
-        }
-        return result;
-    }
-
-    protected String buildStatusString(String taskName, String componentName, String message) {
-        StringBuffer result = new StringBuffer();
-        result.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
-        result.append("jbi-task xmlns = \"http://java/sun.com/xml/ns/management-message\">");
-        result.append("<component-task-result>");
-        result.append("<component-name>");
-        result.append(componentName);
-        result.append("</component-name>");
-        result.append("<component-task-result-details>");
-        result.append("<task-result-details>");
-        result.append("<task-id>");
-        result.append(taskName);
-        result.append("</task-id>");
-        result.append("<task-result>FAILED</task-result>");
-        result.append("<message-type>ERROR</message-type>");
-        result.append("<task-status-msg>");
-        result.append("<msg-loc-info>");
-        result.append("<loc-token>");
-        result.append(" ");
-        result.append("</loc-token>");
-        result.append("<loc-message>");
-        result.append(message);
-        result.append("</loc-message>");
-        result.append("</msg-loc-info>");
-        result.append("</task-status-msg>");
-        result.append("</task-result-details>");
-        result.append(message);
-        result.append("</component-task-result-details>");
-        result.append("</component-task-result>");
-        return result.toString();
-    }
-    
-    
-    /**
-     * Get an array of MBeanAttributeInfo
-     * 
-     * @return array of AttributeInfos
-     * @throws JMException
-     */
-    public MBeanAttributeInfo[] getAttributeInfos() throws JMException {
-        AttributeInfoHelper helper = new AttributeInfoHelper();
-        helper.addAttribute(getObjectToManage(), "deployedServiceAssemblies", "list of deployed SAs");
-        return AttributeInfoHelper.join(super.getAttributeInfos(), helper.getAttributeInfos());
-    }
-
-    /**
-     * Get an array of MBeanOperationInfo
-     * 
-     * @return array of OperationInfos
-     * @throws JMException
-     */
-    public MBeanOperationInfo[] getOperationInfos() throws JMException {
-        OperationInfoHelper helper = new OperationInfoHelper();
-        ParameterHelper ph = helper.addOperation(getObjectToManage(), "deploy", 1, "deploy An SA");
-        ph.setDescription(0, "saZipURL", "location of SA zip file");
-        ph = helper.addOperation(getObjectToManage(), "undeploy", 1, "undeploy An SA");
-        ph.setDescription(0, "saName", "SA name");
-        ph = helper.addOperation(getObjectToManage(), "getDeployedServiceUnitList", 1,
-                "list of SU's currently deployed");
-        ph.setDescription(0, "componentName", "Component name");
-        ph = helper.addOperation(getObjectToManage(), "getServiceAssemblyDescriptor", 1, "Get descriptor for a SA");
-        ph.setDescription(0, "saName", "SA name");
-        ph = helper.addOperation(getObjectToManage(), "getDeployedServiceAssembliesForComponent", 1,
-                "list of SA's for a Component");
-        ph.setDescription(0, "componentName", "Component name");
-        ph = helper.addOperation(getObjectToManage(), "getComponentsForDeployedServiceAssembly", 1,
-                "list of Components  for a SA");
-        ph.setDescription(0, "saName", "SA name");
-        ph = helper.addOperation(getObjectToManage(), "isDeployedServiceUnit", 2, "is SU deployed at a Component ?");
-        ph.setDescription(0, "componentName", "Component name");
-        ph.setDescription(1, "suName", "SU name");
-        ph = helper
-                .addOperation(getObjectToManage(), "canDeployToComponent", 1, "Can a SU be deployed to a Component?");
-        ph.setDescription(0, "componentName", "Component name");
-        ph = helper.addOperation(getObjectToManage(), "start", 1, "start an SA");
-        ph.setDescription(0, "saName", "SA name");
-        ph = helper.addOperation(getObjectToManage(), "stop", 1, "stop an SA");
-        ph.setDescription(0, "saName", "SA name");
-        ph = helper.addOperation(getObjectToManage(), "shutDown", 1, "shutDown an SA");
-        ph.setDescription(0, "saName", "SA name");
-        ph = helper.addOperation(getObjectToManage(), "getState", 1, "Running state of an SA");
-        ph.setDescription(0, "saName", "SA name");
-        return OperationInfoHelper.join(super.getOperationInfos(), helper.getOperationInfos());
-    }
 }

Added: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/Endpoint.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/Endpoint.java?rev=382984&view=auto
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/Endpoint.java (added)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/Endpoint.java Fri Mar  3 16:31:49 2006
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2005-2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.framework;
+
+import java.beans.PropertyChangeListener;
+
+import javax.management.JMException;
+import javax.management.MBeanAttributeInfo;
+import javax.management.MBeanOperationInfo;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+
+import org.apache.servicemix.jbi.management.AttributeInfoHelper;
+import org.apache.servicemix.jbi.management.MBeanInfoProvider;
+import org.apache.servicemix.jbi.management.OperationInfoHelper;
+import org.apache.servicemix.jbi.servicedesc.AbstractServiceEndpoint;
+import org.apache.servicemix.jbi.util.DOMUtil;
+
+public class Endpoint implements EndpointMBean, MBeanInfoProvider {
+
+    private AbstractServiceEndpoint endpoint;
+    private EndpointRegistry endpointRegistry;
+    
+    public Endpoint(AbstractServiceEndpoint endpoint, EndpointRegistry endpointRegistry) {
+        this.endpoint = endpoint;
+        this.endpointRegistry = endpointRegistry;
+    }
+
+    public String getEndpointName() {
+        return endpoint.getEndpointName();
+    }
+
+    public QName[] getInterfaces() {
+        return endpoint.getInterfaces();
+    }
+
+    public QName getServiceName() {
+        return endpoint.getServiceName();
+    }
+    
+    public String getReference() {
+        try {
+            return DOMUtil.asIndentedXML(endpoint.getAsReference(null));
+        } catch (TransformerException e) {
+            return null;
+        }
+    }
+    
+    public String getWSDL() {
+        try {
+            return DOMUtil.asXML(endpointRegistry.getEndpointDescriptor(endpoint));
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    public String getComponentName() {
+        return endpoint.getComponentNameSpace().getName();
+    }
+
+    public MBeanAttributeInfo[] getAttributeInfos() throws JMException {
+        AttributeInfoHelper helper = new AttributeInfoHelper();
+        helper.addAttribute(getObjectToManage(), "endpointName", "name of the endpoint");
+        helper.addAttribute(getObjectToManage(), "serviceName", "name of the service");
+        helper.addAttribute(getObjectToManage(), "componentName", "component name of the service unit");
+        helper.addAttribute(getObjectToManage(), "interfaces", "interfaces implemented by this endpoint");
+        return helper.getAttributeInfos();
+    }
+
+    public MBeanOperationInfo[] getOperationInfos() throws JMException {
+        OperationInfoHelper helper = new OperationInfoHelper();
+        helper.addOperation(getObjectToManage(), "getReference", "retrieve the endpoint reference");
+        helper.addOperation(getObjectToManage(), "getWSDL", "retrieve the wsdl description of this endpoint");
+        return helper.getOperationInfos();
+    }
+
+    public Object getObjectToManage() {
+        return this;
+    }
+
+    public String getName() {
+        return endpoint.getServiceName().toString() + endpoint.getEndpointName();
+    }
+
+    public String getType() {
+        return "Endpoint";
+    }
+
+    public String getSubType() {
+        // TODO: return internal, external, linked ?
+        return null;
+    }
+
+    public String getDescription() {
+        return null;
+    }
+
+    public void setPropertyChangeListener(PropertyChangeListener l) {
+    }
+
+}

Added: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointMBean.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointMBean.java?rev=382984&view=auto
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointMBean.java (added)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointMBean.java Fri Mar  3 16:31:49 2006
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2005-2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.framework;
+
+import javax.xml.namespace.QName;
+
+public interface EndpointMBean {
+
+    public String getEndpointName();
+
+    public QName[] getInterfaces();
+
+    public QName getServiceName();
+    
+    public String getComponentName();
+    
+    public String getReference();
+    
+    public String getWSDL();
+
+}

Modified: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointRegistry.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointRegistry.java?rev=382984&r1=382983&r2=382984&view=diff
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointRegistry.java (original)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/EndpointRegistry.java Fri Mar  3 16:31:49 2006
@@ -24,10 +24,14 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.DocumentFragment;
 
+import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
+
 import javax.jbi.JBIException;
 import javax.jbi.component.Component;
 import javax.jbi.component.ComponentContext;
 import javax.jbi.servicedesc.ServiceEndpoint;
+import javax.management.JMException;
+import javax.management.ObjectName;
 import javax.wsdl.Definition;
 import javax.wsdl.Port;
 import javax.wsdl.Service;
@@ -37,6 +41,7 @@
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
+import java.util.Map;
 import java.util.Set;
 
 /**
@@ -48,15 +53,18 @@
     
     private static final Log logger = LogFactory.getLog(EndpointRegistry.class);
     
-    private ComponentRegistry componentRegistry;
+    private Registry registry;
+    
+    private Map endpoints;
 
     /**
      * Constructor
      * 
      * @param cr
      */
-    public EndpointRegistry(ComponentRegistry cr) {
-        this.componentRegistry = cr;
+    public EndpointRegistry(Registry registry) {
+        this.registry = registry;
+        this.endpoints = new ConcurrentHashMap();
     }
 
     /**
@@ -141,10 +149,18 @@
      * @param serviceEndpoint
      */
     public synchronized void activateEndpoint(ComponentContext provider, InternalEndpoint serviceEndpoint) {
-        ComponentConnector cc = componentRegistry.getLocalComponentConnector(serviceEndpoint.getComponentNameSpace());
+        ComponentConnector cc = registry.getLocalComponentConnector(serviceEndpoint.getComponentNameSpace());
         if (cc != null) {
             cc.addActiveEndpoint(serviceEndpoint);
         }
+        try {
+            Endpoint endpoint = new Endpoint(serviceEndpoint, this);
+            ObjectName objectName = registry.getContainer().getManagementContext().createObjectName(endpoint);
+            registry.getContainer().getManagementContext().registerMBean(objectName, endpoint, EndpointMBean.class);
+            endpoints.put(serviceEndpoint, endpoint);
+        } catch (JMException e) {
+            logger.error("Could not register MBean for endpoint", e);
+        }
     }
 
     /**
@@ -154,10 +170,18 @@
      * @param serviceEndpoint
      */
     public void deactivateEndpoint(ComponentContext provider, InternalEndpoint serviceEndpoint) {
-        ComponentConnector cc = componentRegistry.getLocalComponentConnector(serviceEndpoint.getComponentNameSpace());
+        ComponentConnector cc = registry.getLocalComponentConnector(serviceEndpoint.getComponentNameSpace());
         if (cc != null) {
             cc.removeActiveEndpoint(serviceEndpoint);
         }
+        Endpoint ep = (Endpoint) endpoints.remove(serviceEndpoint);
+        if (ep != null) {
+            try {
+                registry.getContainer().getManagementContext().unregisterMBean(ep);
+            } catch (JBIException e) {
+                logger.error("Could not unregister MBean for endpoint", e);
+            }
+        }
     }
 
     /**
@@ -193,7 +217,7 @@
             throw new JBIException("Descriptors can not be queried for external endpoints");
         }
         AbstractServiceEndpoint se = (AbstractServiceEndpoint) endpoint;
-        Component component = componentRegistry.getComponent(se.getComponentNameSpace());
+        Component component = registry.getComponent(se.getComponentNameSpace());
         return component.getServiceDescription(endpoint);
     }
 
@@ -206,7 +230,7 @@
      * @param externalEndpoint the external endpoint to be registered, must be non-null.
      */
     public void registerExternalEndpoint(ComponentContextImpl provider, ServiceEndpoint externalEndpoint) {
-        ComponentConnector cc = componentRegistry.getLocalComponentConnector(provider.getComponentNameSpace());
+        ComponentConnector cc = registry.getLocalComponentConnector(provider.getComponentNameSpace());
         if (cc != null) {
             cc.addExternalActiveEndpoint(new ExternalEndpoint(cc.getComponentNameSpace(), externalEndpoint));
         }
@@ -221,7 +245,7 @@
      * @param externalEndpoint the external endpoint to be deregistered; must be non-null.
      */
     public void deregisterExternalEndpoint(ComponentContextImpl provider, ServiceEndpoint externalEndpoint) {
-        ComponentConnector cc = componentRegistry.getLocalComponentConnector(provider.getComponentNameSpace());
+        ComponentConnector cc = registry.getLocalComponentConnector(provider.getComponentNameSpace());
         if (cc != null) {
             cc.removeExternalActiveEndpoint(externalEndpoint);
         }
@@ -263,7 +287,7 @@
      * cannot be resolved.
      */
     public ServiceEndpoint resolveEndpointReference(DocumentFragment epr) {
-        Collection connectors = componentRegistry.getLocalComponentConnectors();
+        Collection connectors = registry.getLocalComponentConnectors();
         for (Iterator iter = connectors.iterator(); iter.hasNext();) {
             LocalComponentConnector connector = (LocalComponentConnector) iter.next();
             ServiceEndpoint se = connector.getComponent().resolveEndpointReference(epr);
@@ -349,33 +373,7 @@
         Set set = getEndpointsByName(serviceName, getInternalEndpoints());
         if (!set.isEmpty()) {
             InternalEndpoint endpoint = (InternalEndpoint) set.iterator().next();
-            result = componentRegistry.getComponentConnector(endpoint.getComponentNameSpace());
-        }
-        return result;
-    }
-
-    /**
-     * Utility method to get a ComponentConnector from an InterfaceName
-     * 
-     * @param interfaceName
-     * @return the ComponentConnector
-     */
-    public ComponentConnector getComponentConnector(QName interfaceName) {
-        ComponentConnector result = null;
-        for (Iterator i = getInternalEndpoints().iterator();i.hasNext();) {
-            InternalEndpoint endpoint = (InternalEndpoint) i.next();
-            QName[] interfaces = endpoint.getInterfaces();
-            if (interfaces != null) {
-                if (interfaceName != null) {
-                    for (int k = 0;k < interfaces.length;k++) {
-                        QName qn = interfaces[k];
-                        if (qn != null && qn.equals(interfaceName)) {
-                            result = componentRegistry.getComponentConnector(endpoint.getComponentNameSpace());
-                            break;
-                        }
-                    }
-                }
-            }
+            result = registry.getComponentConnector(endpoint.getComponentNameSpace());
         }
         return result;
     }
@@ -386,7 +384,7 @@
             for (Iterator i = getInternalEndpoints().iterator();i.hasNext();) {
                 InternalEndpoint endpoint = (InternalEndpoint) i.next();
                 if (endpoint.getEndpointName().equals(endpointName)) {
-                    result = componentRegistry.getComponentConnector(endpoint.getComponentNameSpace());
+                    result = registry.getComponentConnector(endpoint.getComponentNameSpace());
                     break;
                 }
             }
@@ -413,7 +411,7 @@
      */
     protected Set getInternalEndpoints() {
         Set answer = new HashSet();
-        for (Iterator iter = this.componentRegistry.getComponentConnectors().iterator();iter.hasNext();) {
+        for (Iterator iter = this.registry.getComponentConnectors().iterator();iter.hasNext();) {
             ComponentConnector cc = (ComponentConnector) iter.next();
             answer.addAll(cc.getActiveEndpoints());
         }
@@ -425,7 +423,7 @@
      */
     protected Set getExternalEndpoints() {
         Set answer = new HashSet();
-        for (Iterator iter = this.componentRegistry.getComponentConnectors().iterator(); iter.hasNext();) {
+        for (Iterator iter = this.registry.getComponentConnectors().iterator(); iter.hasNext();) {
             ComponentConnector cc = (ComponentConnector) iter.next();
             answer.addAll(cc.getExternalActiveEndpoints());
         }

Modified: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallationService.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallationService.java?rev=382984&r1=382983&r2=382984&view=diff
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallationService.java (original)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallationService.java Fri Mar  3 16:31:49 2006
@@ -24,6 +24,7 @@
 
 import javax.jbi.JBIException;
 import javax.jbi.management.DeploymentException;
+import javax.jbi.management.InstallationServiceMBean;
 import javax.jbi.management.InstallerMBean;
 import javax.management.Attribute;
 import javax.management.JMException;
@@ -44,6 +45,8 @@
 import org.apache.servicemix.jbi.deployment.InstallationDescriptorExtension;
 import org.apache.servicemix.jbi.deployment.SharedLibrary;
 import org.apache.servicemix.jbi.deployment.SharedLibraryList;
+import org.apache.servicemix.jbi.loaders.ClassLoaderService;
+import org.apache.servicemix.jbi.loaders.InstallationClassLoader;
 import org.apache.servicemix.jbi.management.BaseSystemService;
 import org.apache.servicemix.jbi.management.ManagementContext;
 import org.apache.servicemix.jbi.management.OperationInfoHelper;
@@ -56,7 +59,7 @@
  * 
  * @version $Revision$
  */
-public class InstallationService extends BaseSystemService implements FrameworkInstallationService{
+public class InstallationService extends BaseSystemService implements InstallationServiceMBean {
     private static final Log log=LogFactory.getLog(InstallationService.class);
     private EnvironmentContext environmentContext;
     private ManagementContext managementContext;
@@ -205,7 +208,7 @@
      *            true if the component is to be deleted as well.
      * @return - true if the operation was successful, otherwise false.
      */
-    public boolean unloadInstaller(String componentName, boolean isToBeDeleted){
+    public boolean unloadInstaller(String componentName, boolean isToBeDeleted) {
         boolean result=false;
         try {
             container.getBroker().suspend();
@@ -220,7 +223,7 @@
                 }
             }
         } catch(JBIException e) {
-            String errStr = "problem shutting down Component: " + componentName;
+            String errStr = "Problem shutting down Component: " + componentName;
             log.error(errStr, e);
         } finally {
             container.getBroker().resume();
@@ -261,16 +264,12 @@
      *            the name of the shared library to uninstall.
      * @return - true iff the uninstall was successful.
      */
-    public boolean uninstallSharedLibrary(String aSharedLibName){
-        boolean result=false;
+    public boolean uninstallSharedLibrary(String aSharedLibName) {
+        // TODO: should check existence of shared library
+        // and that it is not currently in use
         classLoaderService.removeSharedLibrary(aSharedLibName);
-        try{
-            environmentContext.removeSharedLibraryDirectory(aSharedLibName);
-            result=true;
-        }catch(IOException e){
-            log.error("Failed to remove shared library directory");
-        }
-        return result;
+        environmentContext.removeSharedLibraryDirectory(aSharedLibName);
+        return true;
     }
 
     /**
@@ -288,7 +287,7 @@
     }
     
     protected Class getServiceMBean() {
-        return FrameworkInstallationService.class;
+        return InstallationServiceMBean.class;
     }
 
     /**
@@ -446,10 +445,12 @@
                     FileUtil.deleteFile(installationDir);
                 }
                 if(!tmpDirectory.renameTo(installationDir)){
-                    throw new DeploymentException("Unable to rename "+tmpDirectory+" to "+installationDir);
+                    throw new DeploymentException("Unable to rename " + tmpDirectory + " to " + installationDir);
+                }
+                if (log.isDebugEnabled()) {
+                    log.debug("Moved " + tmpDirectory + " to " + installationDir);
                 }
-                log.info("moved "+tmpDirectory+" to "+installationDir);
-                classLoaderService.addSharedLibrary(installationDir,descriptor);
+                classLoaderService.addSharedLibrary(installationDir, descriptor);
             }catch(IOException e){
                 log.error("Deployment of Shared Library failed",e);
                 // remove any files created for installation
@@ -468,13 +469,15 @@
             File oldInstallationDir=environmentContext.getInstallationDirectory(name);
             // try and delete the old version ? - maybe should leave around ??
             if(!FileUtil.deleteFile(oldInstallationDir)){
-                log.warn("Failed to delete old installation directory: "+oldInstallationDir.getPath());
+                log.warn("Failed to delete old installation directory: " + oldInstallationDir.getPath());
             }
             File componentRoot=environmentContext.createComponentRootDirectory(name);
             // this will get the new one
             File installationDir=environmentContext.getInstallationDirectory(name);
             tmpDirectory.renameTo(installationDir);
-            log.info("moved "+tmpDirectory+" to "+installationDir);
+            if (log.isDebugEnabled()) {
+                log.debug("Moved " + tmpDirectory + " to " + installationDir);
+            }
             result=initializeInstaller(installationDir,componentRoot,descriptor);
             return result;
         }catch(IOException e){

Modified: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallerMBeanImpl.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallerMBeanImpl.java?rev=382984&r1=382983&r2=382984&view=diff
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallerMBeanImpl.java (original)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallerMBeanImpl.java Fri Mar  3 16:31:49 2006
@@ -25,6 +25,7 @@
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.servicemix.jbi.container.JBIContainer;
+import org.apache.servicemix.jbi.loaders.ClassLoaderUtil;
 
 /**
  * InstallerMBean defines standard installation and uninstallation controls for Binding Components and Service Engines.

Modified: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/LocalComponentConnector.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/LocalComponentConnector.java?rev=382984&r1=382983&r2=382984&view=diff
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/LocalComponentConnector.java (original)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/LocalComponentConnector.java Fri Mar  3 16:31:49 2006
@@ -28,12 +28,13 @@
 import javax.jbi.servicedesc.ServiceEndpoint;
 import javax.management.ObjectName;
 
-
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.servicemix.jbi.container.ActivationSpec;
+import org.apache.servicemix.jbi.container.JBIContainer;
 import org.apache.servicemix.jbi.management.ManagementContext;
 import org.apache.servicemix.jbi.messaging.DeliveryChannelImpl;
+import org.apache.servicemix.jbi.messaging.MessagingStats;
 import org.apache.servicemix.jbi.util.XmlPersistenceSupport;
 
 /**
@@ -49,20 +50,19 @@
     private ServiceUnitManager suManager;
     private ComponentContextImpl context;
     private ActivationSpec activationSpec;
-    private DeliveryChannelImpl deliveryChannel;
     private ObjectName extendedMBeanName;
     private ComponentMBeanImpl componentMBean;
-    private ComponentStatsMBeanImpl componentStatsMBean;
+    private ObjectName componentMBeanName;
+    private ComponentStats componentStatsMBean;
+    private ObjectName componentStatsMBeanName;
+    private JBIContainer container;
+    private MessagingStats messagingStats;
+    private boolean exchangeThrottling;
+    private long throttlingTimeout = 100;
+    private int throttlingInterval = 1;
     private boolean pojo;
 
     /**
-     * Default Constructor
-     */
-    public LocalComponentConnector() {
-        super();
-    }
-
-    /**
      * Construct with it's id and delivery channel Id
      * 
      * @param name
@@ -72,16 +72,17 @@
      * @param binding
      * @param service
      */
-    public LocalComponentConnector(ComponentNameSpace name, String description, Component component,
-            DeliveryChannelImpl dc, boolean binding, boolean service) {
+    public LocalComponentConnector(JBIContainer container, ComponentNameSpace name, String description, Component component,
+            boolean binding, boolean service) {
         super(name);
+        this.container = container;
         this.component = component;
-        this.deliveryChannel = dc;
         packet.setDescription(description);
         packet.setBinding(binding);
         packet.setService(service);
         this.componentMBean = new ComponentMBeanImpl(this);
-        this.componentStatsMBean = new ComponentStatsMBeanImpl(this);
+        this.componentStatsMBean = new ComponentStats(this);
+        this.messagingStats = new MessagingStats(name.getName());
     }
     
     
@@ -93,13 +94,11 @@
      */
     public ObjectName registerMBeans(ManagementContext context) throws JBIException{
         try{
-            ObjectName result = context.createObjectName(componentMBean);
-            context.registerMBean(result, componentMBean, ComponentMBean.class);
-            componentMBean.setObjectName(result);
-            ObjectName objName = context.createObjectName(componentStatsMBean);
-            context.registerMBean(objName, componentStatsMBean, ComponentStatsMBean.class);
-            componentStatsMBean.setObjectName(objName);
-            return result;
+            componentMBeanName = context.createObjectName(componentMBean);
+            context.registerMBean(componentMBeanName, componentMBean, ComponentMBean.class);
+            componentStatsMBeanName = context.createObjectName(componentStatsMBean);
+            context.registerMBean(componentStatsMBeanName, componentStatsMBean, ComponentStatsMBean.class);
+            return componentMBeanName;
         }catch(Exception e){
             String errorStr="Failed to register MBeans";
             log.error(errorStr,e);
@@ -113,8 +112,8 @@
      * @throws JBIException
      */
     public void unregisterMbeans(ManagementContext context) throws JBIException{
-        context.unregisterMBean(componentMBean.getObjectName());
-        context.unregisterMBean(componentStatsMBean.getObjectName());
+        context.unregisterMBean(componentMBeanName);
+        context.unregisterMBean(componentStatsMBeanName);
     }
 
     /**
@@ -206,7 +205,7 @@
      * @return Returns the deliveryChannel.
      */
     public DeliveryChannelImpl getDeliveryChannel() {
-        return deliveryChannel;
+        return (DeliveryChannelImpl) context.getDeliveryChannel();
     }
 
     /**
@@ -214,7 +213,7 @@
      *            The deliveryChannel to set.
      */
     public void setDeliveryChannel(DeliveryChannelImpl deliveryChannel) {
-        this.deliveryChannel = deliveryChannel;
+        context.setDeliveryChannel(deliveryChannel);
     }
 
     /**
@@ -236,8 +235,8 @@
     /**
      * @return Returns the mbeanName.
      */
-    public ObjectName getMbeanName() {
-        return componentMBean.getObjectName();
+    public ObjectName getMBeanName() {
+        return componentMBeanName;
     }
 
     /**
@@ -250,14 +249,14 @@
     /**
     * @return Returns the stats mbeanName.
     */
-   public ObjectName getStatsMbeanName() {
-       return componentStatsMBean.getObjectName();
+   public ObjectName getStatsMBeanName() {
+       return componentStatsMBeanName;
    }
 
    /**
     * @return Returns the ComponentMBean
     */
-   public ComponentStatsMBeanImpl getComponentStatsMBean() {
+   public ComponentStats getComponentStatsMBean() {
        return componentStatsMBean;
    }
 
@@ -283,6 +282,10 @@
      */
     public void init() throws JBIException {
         if (context != null && component != null) {
+            DeliveryChannelImpl channel = new DeliveryChannelImpl(container, context.getComponentName());
+            channel.setConnector(this);
+            channel.setContext(context);
+            context.setDeliveryChannel(channel);
             ClassLoader loader = Thread.currentThread().getContextClassLoader();
             try {
                 Thread.currentThread().setContextClassLoader(getLifeCycle().getClass().getClassLoader());
@@ -385,4 +388,74 @@
         }
         return result;
     }
+
+    /**
+     * @return Returns the container.
+     */
+    public JBIContainer getContainer() {
+        return container;
+    }
+
+    /**
+     * @return Returns the messagingStats.
+     */
+    public MessagingStats getMessagingStats() {
+        return messagingStats;
+    }
+
+
+    /**
+     * Is MessageExchange sender throttling enabled ?
+     * 
+     * @return true if throttling enabled
+     */
+    public boolean isExchangeThrottling() {
+        return exchangeThrottling;
+    }
+
+    /**
+     * Set message throttling
+     * 
+     * @param value
+     */
+    public void setExchangeThrottling(boolean value) {
+        this.exchangeThrottling = value;
+    }
+
+    /**
+     * Get the throttling timeout
+     * 
+     * @return throttling tomeout (ms)
+     */
+    public long getThrottlingTimeout() {
+        return throttlingTimeout;
+    }
+
+    /**
+     * Set the throttling timout
+     * 
+     * @param value (ms)
+     */
+    public void setThrottlingTimeout(long value) {
+        throttlingTimeout = value;
+    }
+
+    /**
+     * Get the interval for throttling - number of Exchanges set before the throttling timeout is applied
+     * 
+     * @return interval for throttling
+     */
+    public int getThrottlingInterval() {
+        return throttlingInterval;
+    }
+
+    /**
+     * Set the throttling interval number of Exchanges set before the throttling timeout is applied
+     * 
+     * @param value
+     */
+    public void setThrottlingInterval(int value) {
+        throttlingInterval = value;
+    }
+
 }

Modified: incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/ManagementSupport.java
URL: http://svn.apache.org/viewcvs/incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/ManagementSupport.java?rev=382984&r1=382983&r2=382984&view=diff
==============================================================================
--- incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/ManagementSupport.java (original)
+++ incubator/servicemix/trunk/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/ManagementSupport.java Fri Mar  3 16:31:49 2006
@@ -17,9 +17,19 @@
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.servicemix.jbi.util.DOMUtil;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
 
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.jbi.management.DeploymentException;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
 
 /**
  * ManagementMessageHelper is a class that ease the building of management messages. 
@@ -29,25 +39,33 @@
     private static final Log logger = LogFactory.getLog(ManagementSupport.class);
 
     public static class Message {
+        private boolean isCauseFramework;
         private String task;
-        private String component;
         private String result;
         private Exception exception;
         private String type;
         private String message;
+        private String component;
+        private String locale;
         
-        public String getComponent() {
-            return component;
-        }
-        public void setComponent(String component) {
-            this.component = component;
-        }
         public Exception getException() {
             return exception;
         }
         public void setException(Exception exception) {
             this.exception = exception;
         }
+        public boolean isCauseFramework() {
+            return isCauseFramework;
+        }
+        public void setCauseFramework(boolean isCauseFramework) {
+            this.isCauseFramework = isCauseFramework;
+        }
+        public String getMessage() {
+            return message;
+        }
+        public void setMessage(String message) {
+            this.message = message;
+        }
         public String getResult() {
             return result;
         }
@@ -66,104 +84,200 @@
         public void setType(String type) {
             this.type = type;
         }
-        public String getMessage() {
-            return message;
+        public String getComponent() {
+            return component;
         }
-        public void setMessage(String message) {
-            this.message = message;
+        public void setComponent(String component) {
+            this.component = component;
+        }
+        public String getLocale() {
+            return locale;
         }
+        public void setLocale(String locale) {
+            this.locale = locale;
+        }
+    }
+    
+    public static Exception failure(String task, String info) throws Exception {
+        return failure(task, info, null, null);
+    }
+    
+    public static Exception failure(String task, List componentResults) throws Exception {
+        return failure(task, null, null, componentResults);
+    }
+    
+    public static Exception failure(String task, String info, Exception e) throws Exception {
+        return failure(task, info, e, null);
+    }
+    
+    public static Exception failure(String task, String info, Exception e, List componentResults) throws Exception {
+        ManagementSupport.Message msg = new ManagementSupport.Message();
+        msg.setTask(task);
+        msg.setResult("FAILED");
+        msg.setType("ERROR");
+        msg.setException(e);
+        msg.setMessage(info);
+        return new Exception(ManagementSupport.createFrameworkMessage(msg, componentResults));
+    }
+
+    public static String createSuccessMessage(String task) {
+        return createSuccessMessage(task, null, null);
     }
     
-    public static String createComponentMessage(Message msg) {
+    public static String createSuccessMessage(String task, List componentResults) {
+        return createSuccessMessage(task, null, componentResults);
+    }
+    
+    public static String createSuccessMessage(String task, String info) {
+        return createSuccessMessage(task, info, null);
+    }
+
+    public static String createSuccessMessage(String task, String info, List componentResults) {
+        ManagementSupport.Message msg = new ManagementSupport.Message();
+        msg.setTask(task);
+        msg.setResult("SUCCESS");
+        msg.setMessage(info);
+        return ManagementSupport.createFrameworkMessage(msg, componentResults);
+    }
+    
+    public static String createWarningMessage(String task, String info, List componentResults) {
+        ManagementSupport.Message msg = new ManagementSupport.Message();
+        msg.setTask(task);
+        msg.setResult("SUCCESS");
+        msg.setType("WARNING");
+        msg.setMessage(info);
+        return ManagementSupport.createFrameworkMessage(msg, componentResults);
+    }
+
+    public static String createFrameworkMessage(Message fmkMsg, List componentResults) {
         try {
-            StringBuffer sw = new StringBuffer();
-            // component-task-result
-            sw.append("<component-task-result");
-            sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\"");
-            sw.append("\n\t");
-            // component-name
-            sw.append("<component-name>");
-            sw.append(msg.getComponent());
-            sw.append("</component-name>");
-            // component-task-result-details
-            sw.append("\n\t");
-            sw.append("<component-task-result-details>");
-            // task-result-details
-            sw.append("\n\t\t");
-            sw.append("<task-result-details>");
-            // task-id
-            sw.append("\n\t\t\t");
-            sw.append("<task-id>");
-            sw.append(msg.getTask());
-            sw.append("</task-id>");
-            // task-result
-            sw.append("\n\t\t\t");
-            sw.append("<task-result>");
-            sw.append(msg.getResult());
-            sw.append("</task-result>");
-            // message-type
-            if (msg.getType() != null) {
-                sw.append("\n\t\t\t");
-                sw.append("<message-type>");
-                sw.append(msg.getType());
-                sw.append("</message-type>");
-            }
-            // task-status-message
-            if (msg.getMessage() != null) {
-                sw.append("\n\t\t\t");
-                sw.append("<task-status-message>");
-                sw.append("<msg-loc-info>");
-                sw.append("<loc-token/>");
-                sw.append("<loc-message>");
-                sw.append(msg.getMessage());
-                sw.append("</loc-message>");
-                sw.append("</msg-loc-info>");
-                sw.append("</task-status-message>");
+            Document doc = createDocument();
+            Element jbiTask = createChild(doc, "jbi-task");
+            jbiTask.setAttribute("xmlns", "http://java.sun.com/xml/ns/jbi/management-message");
+            jbiTask.setAttribute("version", "1.0");
+            Element jbiTaskResult = createChild(jbiTask, "jbi-task-result");
+            Element frmkTaskResult = createChild(jbiTaskResult, "frmwk-task-result");
+            Element frmkTaskResultDetails = createChild(frmkTaskResult, "frmwk-task-result-details");
+            appendTaskResultDetails(frmkTaskResultDetails, fmkMsg);
+            if (fmkMsg.getLocale() != null) {
+                createChild(frmkTaskResult, "locale", fmkMsg.getLocale());
             }
-            // exception-info
-            if (msg.getException() != null) {
-                sw.append("\n\t\t\t");
-                sw.append("<exception-info>");
-                sw.append("\n\t\t\t\t");
-                sw.append("<nesting-level>1</nesting-level>");
-                sw.append("\n\t\t\t\t");
-                sw.append("<msg-loc-info>");
-                sw.append("\n\t\t\t\t\t");
-                sw.append("<loc-token />");
-                sw.append("\n\t\t\t\t\t");
-                sw.append("<loc-message>");
-                sw.append(msg.getException().getMessage());
-                sw.append("</loc-message>");
-                sw.append("\n\t\t\t\t\t");
-                sw.append("<stack-trace>");
-                StringWriter sw2 = new StringWriter();
-                PrintWriter pw = new PrintWriter(sw2);
-                msg.getException().printStackTrace(pw);
-                pw.close();
-                sw.append("<[CDATA[");
-                sw.append(sw2.toString());
-                sw.append("]]>");
-                sw.append("</stack-trace>");
-                sw.append("\n\t\t\t\t");
-                sw.append("</msg-loc-info>");
-                sw.append("\n\t\t\t");
-                sw.append("</exception-info>");
+            if (componentResults != null) {
+                for (Iterator iter = componentResults.iterator(); iter.hasNext();) {
+                    Element element = (Element) iter.next();
+                    jbiTaskResult.appendChild(doc.importNode(element, true));
+                }
             }
-            // end: task-result-details
-            sw.append("\n\t\t");
-            sw.append("</task-result-details>");
-            // end: component-task-result-details
-            sw.append("\n\t");
-            sw.append("</component-task-result-details>");
-            // end: component-task-result
-            sw.append("\n");
-            sw.append("</component-task-result>");
-            // return result
-            return sw.toString();
+            return DOMUtil.asIndentedXML(doc);
         } catch (Exception e) {
-            logger.warn("Error generating component management message", e);
+            logger.error("Error", e);
             return null;
         }
+    }
+    
+    private static Document createDocument() {
+        try {
+            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+            factory.setNamespaceAware(true);
+            DocumentBuilder builder = factory.newDocumentBuilder();
+            return builder.newDocument();
+        } catch (Exception e) {
+            throw new RuntimeException("Could not create DOM document", e);
+        }
+    }
+    
+    private static Element createChild(Node parent, String name) {
+        return createChild(parent, name, null);
+    }
+    
+    private static Element createChild(Node parent, String name, String text) {
+        Document doc = parent instanceof Document ? (Document) parent : parent.getOwnerDocument();
+        Element child = doc.createElementNS("http://java.sun.com/xml/ns/jbi/management-message", name);
+        if (text != null) {
+            child.appendChild(doc.createTextNode(text));
+        }
+        parent.appendChild(child);
+        return child;
+    }
+    
+    private static void appendTaskResultDetails(Element root, Message fmkMsg) {
+        Element taskResultDetails = createChild(root, "task-result-details");
+        createChild(taskResultDetails, "task-id", fmkMsg.getTask());
+        createChild(taskResultDetails, "task-result", fmkMsg.getResult());
+        if (fmkMsg.getType() != null) {
+            createChild(taskResultDetails, "message-type", fmkMsg.getType());
+        }
+        // task-status-message
+        if (fmkMsg.getMessage() != null) {
+            Element taskStatusMessage = createChild(taskResultDetails, "task-status-message");
+            Element msgLocInfo = createChild(taskStatusMessage, "msg-loc-info");
+            createChild(msgLocInfo, "loc-token");
+            createChild(msgLocInfo, "loc-message", fmkMsg.getMessage());
+        }
+        // exception-info
+        if (fmkMsg.getException() != null) {
+            Element exceptionInfo = createChild(taskResultDetails, "exception-info");
+            createChild(exceptionInfo, "nesting-level", "1");
+            createChild(exceptionInfo, "loc-token");
+            createChild(exceptionInfo, "loc-message", fmkMsg.getException().getMessage());
+            Element stackTrace = createChild(exceptionInfo, "stack-trace");
+            StringWriter sw2 = new StringWriter();
+            PrintWriter pw = new PrintWriter(sw2);
+            fmkMsg.getException().printStackTrace(pw);
+            pw.close();
+            stackTrace.appendChild(root.getOwnerDocument().createCDATASection(sw2.toString()));
+        }
+    }
+    
+    public static DeploymentException componentFailure(String task, String component, String info) {
+        try {
+            Element e = createComponentFailure(task, component, info, null);
+            return new DeploymentException(DOMUtil.asXML(e));
+        } catch (Exception e) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("Error creating management message", e);
+            }
+            return new DeploymentException(info);
+        }
+    }
+    
+    public static Element createComponentMessage(Message msg) {
+        Document doc = createDocument();
+        Element componentTaskResult = createChild(doc, "component-task-result");
+        createChild(componentTaskResult, "component-name", msg.getComponent());
+        Element componentTaskResultDetails = createChild(componentTaskResult, "component-task-result-details");
+        appendTaskResultDetails(componentTaskResultDetails, msg);
+        return componentTaskResult;
+    }
+    
+    public static Element createComponentSuccess(String task, String component) {
+        ManagementSupport.Message msg = new ManagementSupport.Message();
+        msg.setTask(task);
+        msg.setResult("SUCCESS");
+        msg.setComponent(component);
+        return createComponentMessage(msg);
+    }
+    
+    public static Element createComponentFailure(String task, String component, String info, Exception e) {
+        ManagementSupport.Message msg = new ManagementSupport.Message();
+        msg.setTask(task);
+        msg.setResult("FAILED");
+        msg.setType("ERROR");
+        msg.setException(e);
+        msg.setMessage(info);
+        msg.setComponent(component);
+        return createComponentMessage(msg);
+    }
+    
+    public static Element createComponentWarning(String task, String component, String info, Exception e) {
+        ManagementSupport.Message msg = new ManagementSupport.Message();
+        msg.setTask(task);
+        msg.setResult("SUCCESS");
+        msg.setType("WARNING");
+        msg.setException(e);
+        msg.setMessage(info);
+        msg.setComponent(component);
+        return createComponentMessage(msg);
     }
     
 }



Mime
View raw message