Source Code Cross Referenced for DeploymentService.java in  » ESB » servicemix » org » apache » servicemix » jbi » framework » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » ESB » servicemix » org.apache.servicemix.jbi.framework 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Licensed to the Apache Software Foundation (ASF) under one or more
003:         * contributor license agreements.  See the NOTICE file distributed with
004:         * this work for additional information regarding copyright ownership.
005:         * The ASF licenses this file to You under the Apache License, Version 2.0
006:         * (the "License"); you may not use this file except in compliance with
007:         * the License.  You may obtain a copy of the License at
008:         *
009:         *      http://www.apache.org/licenses/LICENSE-2.0
010:         *
011:         * Unless required by applicable law or agreed to in writing, software
012:         * distributed under the License is distributed on an "AS IS" BASIS,
013:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014:         * See the License for the specific language governing permissions and
015:         * limitations under the License.
016:         */
017:        package org.apache.servicemix.jbi.framework;
018:
019:        import java.io.File;
020:        import java.io.IOException;
021:        import java.io.StringReader;
022:        import java.util.ArrayList;
023:        import java.util.Iterator;
024:        import java.util.List;
025:
026:        import javax.jbi.JBIException;
027:        import javax.jbi.component.ServiceUnitManager;
028:        import javax.jbi.management.DeploymentException;
029:        import javax.jbi.management.DeploymentServiceMBean;
030:        import javax.management.JMException;
031:        import javax.management.MBeanAttributeInfo;
032:        import javax.management.MBeanOperationInfo;
033:        import javax.xml.parsers.DocumentBuilder;
034:        import javax.xml.parsers.DocumentBuilderFactory;
035:        import javax.xml.parsers.ParserConfigurationException;
036:
037:        import org.w3c.dom.Document;
038:        import org.w3c.dom.Element;
039:        import org.w3c.dom.NodeList;
040:
041:        import org.xml.sax.InputSource;
042:        import org.xml.sax.SAXException;
043:
044:        import org.apache.commons.logging.Log;
045:        import org.apache.commons.logging.LogFactory;
046:        import org.apache.servicemix.jbi.container.EnvironmentContext;
047:        import org.apache.servicemix.jbi.container.JBIContainer;
048:        import org.apache.servicemix.jbi.container.ServiceAssemblyEnvironment;
049:        import org.apache.servicemix.jbi.deployment.Descriptor;
050:        import org.apache.servicemix.jbi.deployment.DescriptorFactory;
051:        import org.apache.servicemix.jbi.deployment.ServiceAssembly;
052:        import org.apache.servicemix.jbi.deployment.ServiceUnit;
053:        import org.apache.servicemix.jbi.management.AttributeInfoHelper;
054:        import org.apache.servicemix.jbi.management.BaseSystemService;
055:        import org.apache.servicemix.jbi.management.OperationInfoHelper;
056:        import org.apache.servicemix.jbi.management.ParameterHelper;
057:        import org.apache.servicemix.jbi.util.DOMUtil;
058:        import org.apache.servicemix.jbi.util.FileUtil;
059:
060:        /**
061:         * The deployment service MBean allows administrative tools to manage service assembly deployments.
062:         * 
063:         * @version $Revision: 564900 $
064:         */
065:        public class DeploymentService extends BaseSystemService implements 
066:                DeploymentServiceMBean {
067:
068:            private static final Log LOG = LogFactory
069:                    .getLog(DeploymentService.class);
070:
071:            private EnvironmentContext environmentContext;
072:            private Registry registry;
073:
074:            //
075:            // ServiceMix service implementation
076:            //
077:
078:            /**
079:             * Initialize the Service
080:             * 
081:             * @param container
082:             * @throws JBIException 
083:             * @throws DeploymentException
084:             */
085:            public void init(JBIContainer container) throws JBIException {
086:                this .environmentContext = container.getEnvironmentContext();
087:                this .registry = container.getRegistry();
088:                super .init(container);
089:                buildState();
090:            }
091:
092:            protected Class<DeploymentServiceMBean> getServiceMBean() {
093:                return DeploymentServiceMBean.class;
094:            }
095:
096:            public void start() throws javax.jbi.JBIException {
097:                super .start();
098:                String[] sas = registry.getDeployedServiceAssemblies();
099:                for (int i = 0; i < sas.length; i++) {
100:                    try {
101:                        ServiceAssemblyLifeCycle sa = registry
102:                                .getServiceAssembly(sas[i]);
103:                        sa.restore();
104:                    } catch (Exception e) {
105:                        LOG.error(
106:                                "Unable to restore state for service assembly "
107:                                        + sas[i], e);
108:                    }
109:                }
110:            }
111:
112:            /**
113:             * Get an array of MBeanAttributeInfo
114:             * 
115:             * @return array of AttributeInfos
116:             * @throws JMException
117:             */
118:            public MBeanAttributeInfo[] getAttributeInfos() throws JMException {
119:                AttributeInfoHelper helper = new AttributeInfoHelper();
120:                helper.addAttribute(getObjectToManage(),
121:                        "deployedServiceAssemblies", "list of deployed SAs");
122:                return AttributeInfoHelper.join(super .getAttributeInfos(),
123:                        helper.getAttributeInfos());
124:            }
125:
126:            /**
127:             * Get an array of MBeanOperationInfo
128:             * 
129:             * @return array of OperationInfos
130:             * @throws JMException
131:             */
132:            public MBeanOperationInfo[] getOperationInfos() throws JMException {
133:                OperationInfoHelper helper = new OperationInfoHelper();
134:                ParameterHelper ph = helper.addOperation(getObjectToManage(),
135:                        "deploy", 1, "deploy An SA");
136:                ph.setDescription(0, "saZipURL", "location of SA zip file");
137:                ph = helper.addOperation(getObjectToManage(), "undeploy", 1,
138:                        "undeploy An SA");
139:                ph.setDescription(0, "saName", "SA name");
140:                ph = helper.addOperation(getObjectToManage(),
141:                        "getDeployedServiceUnitList", 1,
142:                        "list of SU's currently deployed");
143:                ph.setDescription(0, "componentName", "Component name");
144:                ph = helper.addOperation(getObjectToManage(),
145:                        "getServiceAssemblyDescriptor", 1,
146:                        "Get descriptor for a SA");
147:                ph.setDescription(0, "saName", "SA name");
148:                ph = helper.addOperation(getObjectToManage(),
149:                        "getDeployedServiceAssembliesForComponent", 1,
150:                        "list of SA's for a Component");
151:                ph.setDescription(0, "componentName", "Component name");
152:                ph = helper.addOperation(getObjectToManage(),
153:                        "getComponentsForDeployedServiceAssembly", 1,
154:                        "list of Components  for a SA");
155:                ph.setDescription(0, "saName", "SA name");
156:                ph = helper.addOperation(getObjectToManage(),
157:                        "isDeployedServiceUnit", 2,
158:                        "is SU deployed at a Component ?");
159:                ph.setDescription(0, "componentName", "Component name");
160:                ph.setDescription(1, "suName", "SU name");
161:                ph = helper.addOperation(getObjectToManage(),
162:                        "canDeployToComponent", 1,
163:                        "Can a SU be deployed to a Component?");
164:                ph.setDescription(0, "componentName", "Component name");
165:                ph = helper.addOperation(getObjectToManage(), "start", 1,
166:                        "start an SA");
167:                ph.setDescription(0, "saName", "SA name");
168:                ph = helper.addOperation(getObjectToManage(), "stop", 1,
169:                        "stop an SA");
170:                ph.setDescription(0, "saName", "SA name");
171:                ph = helper.addOperation(getObjectToManage(), "shutDown", 1,
172:                        "shutDown an SA");
173:                ph.setDescription(0, "saName", "SA name");
174:                ph = helper.addOperation(getObjectToManage(), "getState", 1,
175:                        "Running state of an SA");
176:                ph.setDescription(0, "saName", "SA name");
177:                return OperationInfoHelper.join(super .getOperationInfos(),
178:                        helper.getOperationInfos());
179:            }
180:
181:            /**
182:             * Get the description
183:             * 
184:             * @return description
185:             */
186:            public String getDescription() {
187:                return "Allows admin tools to manage service deployments";
188:            }
189:
190:            //
191:            // DeploymentServiceMBean implementation
192:            //
193:
194:            /**
195:             * Deploys the given SA to the JBI environment.
196:             * 
197:             * @param saZipURL String containing the location of the Service Assembly zip file.
198:             * @return Result/Status of the SA deployment in xml format.
199:             * @throws Exception in xml format if complete deployment fails.
200:             */
201:            public String deploy(String saZipURL) throws Exception {
202:                try {
203:                    if (saZipURL == null) {
204:                        throw ManagementSupport.failure("deploy",
205:                                "saZipURL must not be null");
206:                    }
207:                    File tmpDir = null;
208:                    try {
209:                        tmpDir = AutoDeploymentService.unpackLocation(
210:                                environmentContext.getTmpDir(), saZipURL);
211:                    } catch (Exception e) {
212:                        throw ManagementSupport.failure("deploy",
213:                                "Unable to unpack archive: " + saZipURL, e);
214:                    }
215:                    // unpackLocation returns null if no jbi descriptor is found
216:                    if (tmpDir == null) {
217:                        throw ManagementSupport.failure("deploy",
218:                                "Unable to find jbi descriptor: " + saZipURL);
219:                    }
220:                    Descriptor root = null;
221:                    try {
222:                        root = DescriptorFactory.buildDescriptor(tmpDir);
223:                    } catch (Exception e) {
224:                        throw ManagementSupport.failure("deploy",
225:                                "Unable to build jbi descriptor: " + saZipURL,
226:                                e);
227:                    }
228:                    if (root == null) {
229:                        throw ManagementSupport.failure("deploy",
230:                                "Unable to find jbi descriptor: " + saZipURL);
231:                    }
232:                    ServiceAssembly sa = root.getServiceAssembly();
233:                    if (sa == null) {
234:                        throw ManagementSupport.failure("deploy",
235:                                "JBI descriptor is not an assembly descriptor: "
236:                                        + saZipURL);
237:                    }
238:                    return deployServiceAssembly(tmpDir, sa);
239:                } catch (Exception e) {
240:                    LOG.error("Error deploying service assembly", e);
241:                    throw e;
242:                }
243:            }
244:
245:            /**
246:             * Undeploys the given SA from the JBI environment.
247:             * 
248:             * @param saName name of the SA that has to be undeployed.
249:             * @return Result/Status of the SA undeployment.
250:             * @throws Exception if compelete undeployment fails.
251:             */
252:            public String undeploy(String saName) throws Exception {
253:                if (saName == null) {
254:                    throw ManagementSupport.failure("undeploy",
255:                            "SA name must not be null");
256:                }
257:                ServiceAssemblyLifeCycle sa = registry
258:                        .getServiceAssembly(saName);
259:                if (sa == null) {
260:                    throw ManagementSupport.failure("undeploy",
261:                            "SA has not been deployed: " + saName);
262:                }
263:                String state = sa.getCurrentState();
264:                if (!DeploymentServiceMBean.SHUTDOWN.equals(state)) {
265:                    throw ManagementSupport.failure("undeploy",
266:                            "SA must be shut down: " + saName);
267:                }
268:                try {
269:                    // Make sure the all service units in the assembly are shutdown.
270:                    // SUs can have different states (if a previous shutdown failed).
271:                    try {
272:                        sa.shutDown();
273:                    } catch (Exception e) {
274:                        // Ignore
275:                    }
276:
277:                    String result = null;
278:                    String assemblyName = sa.getName();
279:                    registry.unregisterServiceAssembly(assemblyName);
280:                    ServiceUnitLifeCycle[] sus = sa.getDeployedSUs();
281:                    if (sus != null) {
282:                        for (int i = 0; i < sus.length; i++) {
283:                            undeployServiceUnit(sus[i]);
284:                        }
285:                    }
286:                    FileUtil.deleteFile(sa.getEnvironment().getRootDir());
287:
288:                    return result;
289:                } catch (Exception e) {
290:                    LOG.info("Unable to undeploy assembly", e);
291:                    throw e;
292:                }
293:            }
294:
295:            /**
296:             * Returns a list of Service Units that are currently deployed to the given component.
297:             * 
298:             * @param componentName name of the component.
299:             * @return List of deployed ASA Ids.
300:             */
301:            public String[] getDeployedServiceUnitList(String componentName)
302:                    throws Exception {
303:                try {
304:                    ServiceUnitLifeCycle[] sus = registry
305:                            .getDeployedServiceUnits(componentName);
306:                    String[] names = new String[sus.length];
307:                    for (int i = 0; i < names.length; i++) {
308:                        names[i] = sus[i].getName();
309:                    }
310:                    return names;
311:                } catch (Exception e) {
312:                    LOG.info("Unable to get deployed service unit list", e);
313:                    throw e;
314:                }
315:            }
316:
317:            /**
318:             * Returns a list of Service Assemblies deployed to the JBI enviroment.
319:             * 
320:             * @return list of Service Assembly Name's.
321:             */
322:            public String[] getDeployedServiceAssemblies() throws Exception {
323:                try {
324:                    return registry.getDeployedServiceAssemblies();
325:                } catch (Exception e) {
326:                    LOG.info("Unable to get deployed service assemblies", e);
327:                    throw e;
328:                }
329:            }
330:
331:            /**
332:             * Returns the descriptor of the Service Assembly that was deployed to the JBI enviroment.
333:             * 
334:             * @param saName name of the service assembly.
335:             * @return descriptor of the Service Assembly.
336:             */
337:            public String getServiceAssemblyDescriptor(String saName)
338:                    throws Exception {
339:                ServiceAssemblyLifeCycle sa = registry
340:                        .getServiceAssembly(saName);
341:                if (sa != null) {
342:                    return sa.getDescriptor();
343:                } else {
344:                    return null;
345:                }
346:            }
347:
348:            /**
349:             * Returns a list of Service Assemblies that contain SUs for the given component.
350:             * 
351:             * @param componentName name of the component.
352:             * @return list of Service Assembly names.
353:             * @throws Exception if unable to retrieve service assembly list.
354:             */
355:            public String[] getDeployedServiceAssembliesForComponent(
356:                    String componentName) throws Exception {
357:                try {
358:                    return registry
359:                            .getDeployedServiceAssembliesForComponent(componentName);
360:                } catch (Exception e) {
361:                    LOG
362:                            .info(
363:                                    "Error in getDeployedServiceAssembliesForComponent",
364:                                    e);
365:                    throw e;
366:                }
367:            }
368:
369:            /**
370:             * Returns a list of components(to which SUs are targeted for) in a Service Assembly.
371:             * 
372:             * @param saName name of the service assembly.
373:             * @return list of component names.
374:             * @throws Exception if unable to retrieve component list.
375:             */
376:            public String[] getComponentsForDeployedServiceAssembly(
377:                    String saName) throws Exception {
378:                try {
379:                    return registry
380:                            .getComponentsForDeployedServiceAssembly(saName);
381:                } catch (Exception e) {
382:                    LOG.info(
383:                            "Error in getComponentsForDeployedServiceAssembly",
384:                            e);
385:                    throw e;
386:                }
387:            }
388:
389:            /**
390:             * Returns a boolean value indicating whether the SU is currently deployed.
391:             * 
392:             * @param componentName - name of component.
393:             * @param suName - name of the Service Unit.
394:             * @return boolean value indicating whether the SU is currently deployed.
395:             * @throws Exception if unable to return status of service unit.
396:             */
397:            public boolean isDeployedServiceUnit(String componentName,
398:                    String suName) throws Exception {
399:                try {
400:                    return registry.isSADeployedServiceUnit(componentName,
401:                            suName);
402:                } catch (Exception e) {
403:                    LOG.info("Error in isSADeployedServiceUnit", e);
404:                    throw e;
405:                }
406:            }
407:
408:            /**
409:             * Returns a boolean value indicating whether the SU can be deployed to a component.
410:             * 
411:             * @param componentName - name of the component.
412:             * @return boolean value indicating whether the SU can be deployed.
413:             */
414:            public boolean canDeployToComponent(String componentName) {
415:                ComponentMBeanImpl lcc = container.getComponent(componentName);
416:                return lcc != null && lcc.isStarted()
417:                        && lcc.getServiceUnitManager() != null;
418:            }
419:
420:            /**
421:             * Starts the service assembly and puts it in STARTED state.
422:             * 
423:             * @param serviceAssemblyName - name of the service assembly.
424:             * @return Result/Status of this operation.
425:             * @throws Exception if operation fails.
426:             */
427:            public String start(String serviceAssemblyName) throws Exception {
428:                try {
429:                    ServiceAssemblyLifeCycle sa = registry
430:                            .getServiceAssembly(serviceAssemblyName);
431:                    return sa.start(true);
432:                } catch (Exception e) {
433:                    LOG.info("Error in start", e);
434:                    throw e;
435:                }
436:            }
437:
438:            /**
439:             * Stops the service assembly and puts it in STOPPED state.
440:             * 
441:             * @param serviceAssemblyName - name of the service assembly.
442:             * @return Result/Status of this operation.
443:             * @throws Exception if operation fails.
444:             */
445:            public String stop(String serviceAssemblyName) throws Exception {
446:                try {
447:                    ServiceAssemblyLifeCycle sa = registry
448:                            .getServiceAssembly(serviceAssemblyName);
449:                    return sa.stop(true, false);
450:                } catch (Exception e) {
451:                    LOG.info("Error in stop", e);
452:                    throw e;
453:                }
454:            }
455:
456:            /**
457:             * Shutdown the service assembly and puts it in SHUTDOWN state.
458:             * 
459:             * @param serviceAssemblyName - name of the service assembly.
460:             * @return Result/Status of this operation.
461:             * @throws Exception if operation fails.
462:             */
463:            public String shutDown(String serviceAssemblyName) throws Exception {
464:                try {
465:                    ServiceAssemblyLifeCycle sa = registry
466:                            .getServiceAssembly(serviceAssemblyName);
467:                    return sa.shutDown(true);
468:                } catch (Exception e) {
469:                    LOG.info("Error in shutDown", e);
470:                    throw e;
471:                }
472:            }
473:
474:            /**
475:             * Returns the state of service assembly.
476:             * 
477:             * @param serviceAssemblyName - name of the service assembly.
478:             * @return State of the service assembly.
479:             * @throws Exception if operation fails.
480:             */
481:            public String getState(String serviceAssemblyName) throws Exception {
482:                try {
483:                    ServiceAssemblyLifeCycle sa = registry
484:                            .getServiceAssembly(serviceAssemblyName);
485:                    return sa.getCurrentState();
486:                } catch (Exception e) {
487:                    LOG.info("Error in getState", e);
488:                    throw e;
489:                }
490:            }
491:
492:            /**
493:             * See if an Sa is already deployed
494:             * 
495:             * @param serviceAssemblyName - name of the service assembly.
496:             * @return true if already deployed
497:             */
498:            protected boolean isSaDeployed(String serviceAssemblyName) {
499:                return registry.getServiceAssembly(serviceAssemblyName) != null;
500:            }
501:
502:            /**
503:             * Deploy an SA
504:             * 
505:             * @param tmpDir
506:             * @param sa
507:             * @return result/status of the deployment in xml format
508:             * @throws Exception  in xml format
509:             */
510:            protected String deployServiceAssembly(File tmpDir,
511:                    ServiceAssembly sa) throws Exception {
512:                String assemblyName = sa.getIdentification().getName();
513:                ServiceAssemblyEnvironment env = environmentContext
514:                        .getNewServiceAssemblyEnvironment(assemblyName);
515:                File saDirectory = env.getInstallDir();
516:
517:                // move the assembly to a well-named holding area
518:                if (LOG.isDebugEnabled()) {
519:                    LOG.debug("Moving " + tmpDir.getAbsolutePath() + " to "
520:                            + saDirectory.getAbsolutePath());
521:                }
522:                saDirectory.getParentFile().mkdirs();
523:                if (!tmpDir.renameTo(saDirectory)) {
524:                    throw ManagementSupport
525:                            .failure("deploy", "Failed to rename " + tmpDir
526:                                    + " to " + saDirectory);
527:                }
528:                // Check all SUs requirements
529:                ServiceUnit[] sus = sa.getServiceUnits();
530:                if (sus != null) {
531:                    checkSus(saDirectory, sus);
532:                }
533:                // Everything seems ok, so deploy all SUs
534:                int nbFailures = 0;
535:                List<Element> componentResults = new ArrayList<Element>();
536:                List<String> suKeys = new ArrayList<String>();
537:                if (sus != null) {
538:                    for (int i = 0; i < sus.length; i++) {
539:                        File targetDir = null;
540:                        String suName = sus[i].getIdentification().getName();
541:                        String artifact = sus[i].getTarget().getArtifactsZip();
542:                        String componentName = sus[i].getTarget()
543:                                .getComponentName();
544:                        // TODO: skip duplicates
545:                        // Unpack SU
546:                        try {
547:                            File artifactFile = new File(saDirectory, artifact);
548:                            targetDir = env.getServiceUnitDirectory(
549:                                    componentName, suName);
550:                            if (LOG.isDebugEnabled()) {
551:                                LOG.debug("Unpack service unit archive "
552:                                        + artifactFile + " to " + targetDir);
553:                            }
554:                            FileUtil.unpackArchive(artifactFile, targetDir);
555:                        } catch (IOException e) {
556:                            nbFailures++;
557:                            componentResults.add(ManagementSupport
558:                                    .createComponentFailure("deploy",
559:                                            componentName,
560:                                            "Error unpacking service unit", e));
561:                            continue;
562:                        }
563:                        // Deploy it
564:                        boolean success = false;
565:                        try {
566:                            ComponentMBeanImpl lcc = container
567:                                    .getComponent(componentName);
568:                            ServiceUnitManager sum = lcc
569:                                    .getServiceUnitManager();
570:                            ClassLoader cl = Thread.currentThread()
571:                                    .getContextClassLoader();
572:                            try {
573:                                Thread.currentThread().setContextClassLoader(
574:                                        lcc.getComponent().getClass()
575:                                                .getClassLoader());
576:                                String resultMsg = sum.deploy(suName, targetDir
577:                                        .getAbsolutePath());
578:                                success = getComponentTaskResult(resultMsg,
579:                                        componentName, componentResults, true);
580:                            } finally {
581:                                Thread.currentThread()
582:                                        .setContextClassLoader(cl);
583:                            }
584:                            // TODO: need to register the SU somewhere to keep track of its state
585:                        } catch (Exception e) {
586:                            getComponentTaskError(e, componentName,
587:                                    componentResults);
588:                        }
589:                        if (success) {
590:                            suKeys.add(registry.registerServiceUnit(sus[i],
591:                                    assemblyName, targetDir));
592:                        } else {
593:                            nbFailures++;
594:                        }
595:                    }
596:                }
597:                // Note: the jbi spec says that if at least one deployment succeeds, 
598:                // this should be a SUCCESS.  However, ServiceMix handles SA in an
599:                // atomic way: for a given operation on an SA, all operations on SU
600:                // should succeed.  This is clearly a minor violation of the spec.
601:                //
602:                // Failure
603:                if (nbFailures > 0) {
604:                    // Undeploy SUs
605:                    for (Iterator<String> iter = suKeys.iterator(); iter
606:                            .hasNext();) {
607:                        try {
608:                            String suName = iter.next();
609:                            ServiceUnitLifeCycle su = registry
610:                                    .getServiceUnit(suName);
611:                            undeployServiceUnit(su);
612:                        } catch (Exception e) {
613:                            LOG.warn("Error undeploying SU", e);
614:                        }
615:                    }
616:                    // Delete SA deployment directory 
617:                    FileUtil.deleteFile(saDirectory);
618:                    throw ManagementSupport.failure("deploy", componentResults);
619:                    // Success
620:                } else {
621:                    // Register SA
622:                    String[] deployedSUs = suKeys.toArray(new String[suKeys
623:                            .size()]);
624:                    ServiceAssemblyLifeCycle salc = registry
625:                            .registerServiceAssembly(sa, deployedSUs, env);
626:                    salc.writeRunningState();
627:                    // Build result string
628:                    if (nbFailures > 0) {
629:                        return ManagementSupport.createWarningMessage("deploy",
630:                                "Failed to deploy some service units",
631:                                componentResults);
632:                    } else {
633:                        return ManagementSupport.createSuccessMessage("deploy",
634:                                componentResults);
635:                    }
636:                }
637:            }
638:
639:            protected void checkSus(File saDirectory, ServiceUnit[] sus)
640:                    throws Exception {
641:                for (int i = 0; i < sus.length; i++) {
642:                    String suName = sus[i].getIdentification().getName();
643:                    String artifact = sus[i].getTarget().getArtifactsZip();
644:                    String componentName = sus[i].getTarget()
645:                            .getComponentName();
646:                    File artifactFile = new File(saDirectory, artifact);
647:                    if (!artifactFile.exists()) {
648:                        throw ManagementSupport.failure("deploy", "Artifact "
649:                                + artifact + " not found for service unit "
650:                                + suName);
651:                    }
652:                    ComponentMBeanImpl lcc = container
653:                            .getComponent(componentName);
654:                    if (lcc == null) {
655:                        throw ManagementSupport.failure("deploy",
656:                                "Target component " + componentName
657:                                        + " for service unit " + suName
658:                                        + " is not installed");
659:                    }
660:                    if (!lcc.isStarted()) {
661:                        throw ManagementSupport.failure("deploy",
662:                                "Target component " + componentName
663:                                        + " for service unit " + suName
664:                                        + " is not started");
665:                    }
666:                    if (lcc.getServiceUnitManager() == null) {
667:                        throw ManagementSupport.failure("deploy",
668:                                "Target component " + componentName
669:                                        + " for service unit " + suName
670:                                        + " does not accept deployments");
671:                    }
672:                    // TODO: check duplicates here ?
673:                    if (isDeployedServiceUnit(componentName, suName)) {
674:                        throw ManagementSupport.failure("deploy",
675:                                "Service unit " + suName
676:                                        + " is already deployed on component "
677:                                        + componentName);
678:                    }
679:                }
680:            }
681:
682:            protected void getComponentTaskError(Exception exception,
683:                    String component, List<Element> results) {
684:                Element result = null;
685:                try {
686:                    Document doc = parse(exception.getMessage());
687:                    result = getElement(doc, "component-task-result");
688:                } catch (Exception e) {
689:                    result = ManagementSupport.createComponentFailure("deploy",
690:                            component, "Unable to parse result string",
691:                            exception);
692:                }
693:                if (result != null) {
694:                    results.add(result);
695:                }
696:            }
697:
698:            protected boolean getComponentTaskResult(String resultMsg,
699:                    String component, List<Element> results, boolean success) {
700:                Element result = null;
701:                try {
702:                    Document doc = parse(resultMsg);
703:                    result = getElement(doc, "component-task-result");
704:                    Element e = getChildElement(result,
705:                            "component-task-result-details");
706:                    e = getChildElement(e, "task-result-details");
707:                    e = getChildElement(e, "task-result");
708:                    String r = DOMUtil.getElementText(e);
709:                    if (!"SUCCESS".equals(r)) {
710:                        success = false;
711:                    }
712:                } catch (Exception e) {
713:                    // The component did not throw an exception upon deployment,
714:                    // but the result string is not compliant, so issue a warning
715:                    // and consider this is a successfull deployment
716:                    try {
717:                        if (success) {
718:                            result = ManagementSupport.createComponentWarning(
719:                                    "deploy", component,
720:                                    "Unable to parse result string", e);
721:                        } else {
722:                            result = ManagementSupport.createComponentFailure(
723:                                    "deploy", component,
724:                                    "Unable to parse result string", e);
725:                        }
726:                    } catch (Exception e2) {
727:                        LOG.error(e2);
728:                        result = null;
729:                    }
730:                }
731:                if (result != null) {
732:                    results.add(result);
733:                }
734:                return success;
735:            }
736:
737:            protected Document parse(String result)
738:                    throws ParserConfigurationException, SAXException,
739:                    IOException {
740:                DocumentBuilderFactory factory = DocumentBuilderFactory
741:                        .newInstance();
742:                factory.setNamespaceAware(true);
743:                factory.setIgnoringElementContentWhitespace(true);
744:                factory.setIgnoringComments(true);
745:                DocumentBuilder builder = factory.newDocumentBuilder();
746:                return builder.parse(new InputSource(new StringReader(result)));
747:            }
748:
749:            protected Element getElement(Document doc, String name) {
750:                NodeList l = doc.getElementsByTagNameNS(
751:                        "http://java.sun.com/xml/ns/jbi/management-message",
752:                        name);
753:                return (Element) l.item(0);
754:            }
755:
756:            protected Element getChildElement(Element element, String name) {
757:                NodeList l = element.getElementsByTagNameNS(
758:                        "http://java.sun.com/xml/ns/jbi/management-message",
759:                        name);
760:                return (Element) l.item(0);
761:            }
762:
763:            protected void undeployServiceUnit(ServiceUnitLifeCycle su)
764:                    throws DeploymentException {
765:                String name = su.getName();
766:                String componentName = su.getComponentName();
767:                File targetDir = su.getServiceUnitRootPath();
768:                registry.unregisterServiceUnit(su.getKey());
769:                // unpack the artifact
770:                // now get the component and give it a SA
771:                ComponentMBeanImpl component = container
772:                        .getComponent(componentName);
773:                if (component != null) {
774:                    ServiceUnitManager sum = component.getServiceUnitManager();
775:                    if (sum != null) {
776:                        ClassLoader cl = Thread.currentThread()
777:                                .getContextClassLoader();
778:                        try {
779:                            Thread.currentThread().setContextClassLoader(
780:                                    component.getComponent().getClass()
781:                                            .getClassLoader());
782:                            sum.undeploy(name, targetDir.getAbsolutePath());
783:                        } finally {
784:                            Thread.currentThread().setContextClassLoader(cl);
785:                        }
786:                        FileUtil.deleteFile(targetDir);
787:                    }
788:                } else {
789:                    FileUtil.deleteFile(targetDir);
790:                }
791:                LOG.info("UnDeployed ServiceUnit " + name + " from Component: "
792:                        + componentName);
793:            }
794:
795:            /**
796:             * Find runnning state and things deployed before shutdown
797:             */
798:            protected void buildState() {
799:                LOG.info("Restoring service assemblies");
800:                // walk through deployed SA's
801:                File top = environmentContext.getServiceAssembliesDir();
802:                if (top == null || !top.exists() || !top.isDirectory()) {
803:                    return;
804:                }
805:                File[] files = top.listFiles();
806:                if (files == null) {
807:                    return;
808:                }
809:                // Initialize all assemblies
810:                for (int i = 0; i < files.length; i++) {
811:                    if (files[i].isDirectory()) {
812:                        String assemblyName = files[i].getName();
813:                        try {
814:                            ServiceAssemblyEnvironment env = environmentContext
815:                                    .getServiceAssemblyEnvironment(assemblyName);
816:                            Descriptor root = DescriptorFactory
817:                                    .buildDescriptor(env.getInstallDir());
818:                            if (root != null) {
819:                                ServiceAssembly sa = root.getServiceAssembly();
820:                                if (sa != null
821:                                        && sa.getIdentification() != null) {
822:                                    registry.registerServiceAssembly(sa, env);
823:                                }
824:                            }
825:                        } catch (Exception e) {
826:                            LOG.error(
827:                                    "Failed to initialized service assembly: "
828:                                            + assemblyName, e);
829:                        }
830:                    }
831:                }
832:            }
833:
834:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.