KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > container > JBIContainer


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.jbi.container;
18
19 import java.io.File JavaDoc;
20 import java.util.Calendar JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.EventListener JavaDoc;
23 import java.util.MissingResourceException JavaDoc;
24 import java.util.logging.Logger JavaDoc;
25
26 import javax.jbi.JBIException;
27 import javax.jbi.component.Component;
28 import javax.jbi.component.ComponentLifeCycle;
29 import javax.jbi.component.ServiceUnitManager;
30 import javax.jbi.management.DeploymentException;
31 import javax.jbi.management.LifeCycleMBean;
32 import javax.jbi.messaging.ExchangeStatus;
33 import javax.jbi.messaging.MessageExchange;
34 import javax.jbi.messaging.MessagingException;
35 import javax.jbi.servicedesc.ServiceEndpoint;
36 import javax.management.JMException JavaDoc;
37 import javax.management.MBeanServer JavaDoc;
38 import javax.management.ObjectName JavaDoc;
39 import javax.naming.InitialContext JavaDoc;
40 import javax.naming.NamingException JavaDoc;
41 import javax.resource.spi.work.WorkManager JavaDoc;
42 import javax.swing.event.EventListenerList JavaDoc;
43 import javax.transaction.TransactionManager JavaDoc;
44 import javax.xml.namespace.QName JavaDoc;
45
46 import org.apache.commons.logging.Log;
47 import org.apache.commons.logging.LogFactory;
48 import org.apache.geronimo.connector.work.GeronimoWorkManager;
49 import org.apache.servicemix.JbiConstants;
50 import org.apache.servicemix.MessageExchangeListener;
51 import org.apache.servicemix.components.util.ComponentAdaptor;
52 import org.apache.servicemix.components.util.ComponentAdaptorMEListener;
53 import org.apache.servicemix.components.util.ComponentSupport;
54 import org.apache.servicemix.components.util.PojoLifecycleAdaptor;
55 import org.apache.servicemix.components.util.PojoSupport;
56 import org.apache.servicemix.id.IdGenerator;
57 import org.apache.servicemix.jbi.event.ComponentListener;
58 import org.apache.servicemix.jbi.event.EndpointListener;
59 import org.apache.servicemix.jbi.event.ExchangeEvent;
60 import org.apache.servicemix.jbi.event.ExchangeListener;
61 import org.apache.servicemix.jbi.event.ServiceAssemblyListener;
62 import org.apache.servicemix.jbi.event.ServiceUnitListener;
63 import org.apache.servicemix.jbi.framework.AdminCommandsService;
64 import org.apache.servicemix.jbi.framework.AutoDeploymentService;
65 import org.apache.servicemix.jbi.framework.ClientFactory;
66 import org.apache.servicemix.jbi.framework.ComponentContextImpl;
67 import org.apache.servicemix.jbi.framework.ComponentMBeanImpl;
68 import org.apache.servicemix.jbi.framework.ComponentNameSpace;
69 import org.apache.servicemix.jbi.framework.DeploymentService;
70 import org.apache.servicemix.jbi.framework.InstallationService;
71 import org.apache.servicemix.jbi.framework.Registry;
72 import org.apache.servicemix.jbi.management.BaseLifeCycle;
73 import org.apache.servicemix.jbi.management.ManagementContext;
74 import org.apache.servicemix.jbi.messaging.MessageExchangeImpl;
75 import org.apache.servicemix.jbi.nmr.Broker;
76 import org.apache.servicemix.jbi.nmr.DefaultBroker;
77 import org.apache.servicemix.jbi.nmr.flow.Flow;
78 import org.jencks.factory.WorkManagerFactoryBean;
79 import org.w3c.dom.DocumentFragment JavaDoc;
80
81 import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;
82
83 /**
84  * The main container
85  *
86  * @version $Revision: 440289 $
87  */

88 public class JBIContainer extends BaseLifeCycle {
89     /**
90      * Default Container name - must be unique if used in a cluster
91      */

92     public static final String JavaDoc DEFAULT_NAME = "ServiceMix";
93     private static final Log log = LogFactory.getLog(JBIContainer.class);
94     private String JavaDoc name = DEFAULT_NAME;
95     private InitialContext JavaDoc namingContext;
96     private MBeanServer JavaDoc mbeanServer;
97     private TransactionManager JavaDoc transactionManager;
98     private String JavaDoc rootDir = "." + File.separator + "rootDir";
99     private AtomicBoolean started = new AtomicBoolean(false);
100     private AtomicBoolean containerInitialized = new AtomicBoolean(false);
101     private IdGenerator idGenerator = new IdGenerator();
102     protected Broker broker = new DefaultBroker();
103     protected ServiceUnitManager serviceManager;
104     protected ManagementContext managementContext = new ManagementContext();
105     protected EnvironmentContext environmentContext = new EnvironmentContext();
106     protected InstallationService installationService = new InstallationService();
107     protected DeploymentService deploymentService = new DeploymentService();
108     protected AutoDeploymentService autoDeployService = new AutoDeploymentService();
109     protected AdminCommandsService adminCommandsService = new AdminCommandsService();
110     protected ClientFactory clientFactory = new ClientFactory();
111     protected Registry registry = new Registry();
112     protected WorkManager JavaDoc workManager;
113     protected boolean isWorkManagerCreated;
114     protected boolean autoEnlistInTransaction = false;
115     protected boolean persistent = false;
116     protected boolean embedded = false;
117     protected boolean notifyStatistics = false;
118     protected EventListenerList JavaDoc listeners = new EventListenerList JavaDoc();
119     protected EventListener JavaDoc[] configuredListeners;
120     protected boolean useShutdownHook = true;
121     protected transient Thread JavaDoc shutdownHook;
122     
123     /**
124      * Default Constructor
125      */

126     public JBIContainer() {
127     }
128
129     /**
130      * @return Returns the unique nam for the Container
131      */

132     public String JavaDoc getName() {
133         return name;
134     }
135
136     /**
137      * @param name The name to set (must be unique within a cluster)
138      */

139     public void setName(String JavaDoc name) {
140         this.name = name;
141     }
142
143     /**
144      * Get the description
145      *
146      * @return descrption
147      */

148     public String JavaDoc getDescription() {
149         return "ServiceMix JBI Container";
150     }
151
152     /**
153      * @return Returns the flowName.
154      */

155     public String JavaDoc getFlowName() {
156         String JavaDoc flowNames = getDefaultBroker().getFlowNames();
157         if (flowNames == null) {
158             return null;
159         }
160         String JavaDoc[] flows = flowNames.split(",");
161         if (flows.length > 1) {
162             throw new IllegalStateException JavaDoc("Multiple flows have been defined");
163         }
164         return flows[0];
165     }
166
167     /**
168      * @param flowName The flow to set.
169      */

170     public void setFlowName(String JavaDoc flowName) {
171         getDefaultBroker().setFlowNames(flowName);
172     }
173     
174     /**
175      * @return Returns the flowNames.
176      */

177     public String JavaDoc getFlowNames() {
178         return getDefaultBroker().getFlowNames();
179     }
180
181     /**
182      * @param flowNames The flows to set.
183      */

184     public void setFlowNames(String JavaDoc flowNames) {
185         getDefaultBroker().setFlowNames(flowNames);
186     }
187     
188     /**
189      * @return the subscriptionFlowName
190      */

191     public String JavaDoc getSubscriptionFlowName() {
192         return getDefaultBroker().getSubscriptionFlowName();
193     }
194
195     /**
196      * Set the subscription flow name
197      * @param subscriptionFlowName
198      */

199     public void setSubscriptionFlowName(String JavaDoc subscriptionFlowName) {
200         getDefaultBroker().setSubscriptionFlowName(subscriptionFlowName);
201     }
202
203     /**
204      * Set the broker message flow
205      *
206      * @param flow
207      */

208     public void setFlow(Flow flow) {
209         getDefaultBroker().setFlows(new Flow[] { flow });
210     }
211
212     /**
213      * @return the broker message Flow
214      */

215     public Flow getFlow() {
216         Flow[] flows = getDefaultBroker().getFlows();
217         if (flows == null || flows.length == 0) {
218             return null;
219         } else if (flows.length > 1) {
220             throw new IllegalStateException JavaDoc("Multiple flows have been defined");
221         } else {
222             return flows[0];
223         }
224     }
225
226     /**
227      * Set the broker message flows
228      *
229      * @param flow
230      */

231     public void setFlows(Flow[] flows) {
232         getDefaultBroker().setFlows(flows);
233     }
234
235     /**
236      * @return the broker message Flows
237      */

238     public Flow[] getFlows() {
239         return getDefaultBroker().getFlows();
240     }
241
242     public boolean isUseShutdownHook() {
243         return useShutdownHook;
244     }
245
246     /**
247      * Sets whether or not we should use a shutdown handler to close down the
248      * broker cleanly if the JVM is terminated. It is recommended you leave this
249      * enabled.
250      */

251     public void setUseShutdownHook(boolean useShutdownHook) {
252         this.useShutdownHook = useShutdownHook;
253     }
254
255     /**
256      * Get the ManagementContext
257      *
258      * @return the ManagementContext
259      */

260     public ManagementContext getManagementContext() {
261         return managementContext;
262     }
263
264     /**
265      * @return Return the EnvironmentContext
266      */

267     public EnvironmentContext getEnvironmentContext() {
268         return environmentContext;
269     }
270
271     /**
272      * @return Return the registry
273      */

274     public Registry getRegistry() {
275         return registry;
276     }
277     
278     /**
279      * Return the DefaultBroker instance
280      */

281     public DefaultBroker getDefaultBroker() {
282         if (broker == null ||
283             broker instanceof DefaultBroker == false) {
284             throw new IllegalStateException JavaDoc("Broker is not a DefaultBroker");
285         }
286         return (DefaultBroker) broker;
287     }
288     
289     /**
290      * @return Return the NMR broker
291      */

292     public Broker getBroker(){
293         return broker;
294     }
295     
296     /**
297      * Set the Broker to use
298      */

299     public void setBroker(Broker broker) {
300         this.broker = broker;
301     }
302
303     /**
304      * @return true if creates own MBeanServer if none supplied
305      */

306     public boolean isCreateMBeanServer() {
307         return managementContext.isCreateMBeanServer();
308     }
309
310     /**
311      * Set the flag to create own MBeanServer if none supplied
312      *
313      * @param enableJMX
314      */

315     public void setCreateMBeanServer(boolean enableJMX) {
316         managementContext.setCreateMBeanServer(enableJMX);
317     }
318
319     /**
320      * @return Returns the useMBeanServer.
321      */

322     public boolean isUseMBeanServer() {
323         return managementContext.isUseMBeanServer();
324     }
325
326     /**
327      * @param useMBeanServer The useMBeanServer to set.
328      */

329     public void setUseMBeanServer(boolean useMBeanServer) {
330         managementContext.setUseMBeanServer(useMBeanServer);
331     }
332
333     /**
334      * @return Returns the useMBeanServer.
335      */

336     public boolean isCreateJmxConnector() {
337         return managementContext.isCreateJmxConnector();
338     }
339
340     /**
341      * @param useMBeanServer The useMBeanServer to set.
342      */

343     public void setCreateJmxConnector(boolean createJmxConnector) {
344         managementContext.setCreateJmxConnector(createJmxConnector);
345     }
346
347     /**
348      * @return Returns the monitorInstallationDirectory.
349      */

350     public boolean isMonitorInstallationDirectory() {
351         return autoDeployService.isMonitorInstallationDirectory();
352     }
353
354     /**
355      * @param monitorInstallationDirectory The monitorInstallationDirectory to set.
356      */

357     public void setMonitorInstallationDirectory(boolean monitorInstallationDirectory) {
358         autoDeployService.setMonitorInstallationDirectory(monitorInstallationDirectory);
359     }
360     
361     /**
362      * @return Returns the monitorDeploymentDirectory.
363      */

364     public boolean isMonitorDeploymentDirectory(){
365         return autoDeployService.isMonitorDeploymentDirectory();
366     }
367
368     /**
369      * @param monitorDeploymentDirectory The monitorDeploymentDirectory to set.
370      */

371     public void setMonitorDeploymentDirectory(boolean monitorDeploymentDirectory){
372         autoDeployService.setMonitorDeploymentDirectory(monitorDeploymentDirectory);
373     }
374
375     /**
376      * @return Returns the installationDir.
377      */

378     public String JavaDoc getInstallationDirPath() {
379         File JavaDoc dir = environmentContext.getInstallationDir();
380         return dir != null ? dir.getAbsolutePath() : "";
381     }
382
383     /**
384      * Set the installationDir - rge default location is root/<container name>/installation
385      *
386      * @param installationDir
387      */

388     public void setInstallationDirPath(String JavaDoc installationDir) {
389         if (installationDir != null && installationDir.length() > 0) {
390             environmentContext.setInstallationDir(new File JavaDoc(installationDir));
391         }
392     }
393
394     /**
395      * @return Returns the deploymentDir.
396      */

397     public String JavaDoc getDeploymentDirPath() {
398         File JavaDoc dir = environmentContext.getDeploymentDir();
399         return dir != null ? dir.getAbsolutePath() : "";
400     }
401
402     /**
403      * @param deploymentDir The deploymentDir to set.
404      */

405     public void setDeploymentDirPath(String JavaDoc deploymentDir) {
406         if (deploymentDir != null && deploymentDir.length() > 0) {
407             environmentContext.setDeploymentDir(new File JavaDoc(deploymentDir));
408         }
409     }
410
411     /**
412      * @return Returns the statsInterval (in secs).
413      */

414     public int getStatsInterval() {
415         return environmentContext.getStatsInterval();
416     }
417
418     /**
419      * @param statsInterval The statsInterval to set (in secs).
420      */

421     public void setStatsInterval(int statsInterval) {
422         environmentContext.setStatsInterval(statsInterval);
423     }
424     
425     /**
426      * @return Returns the monitorInterval (in secs).
427      */

428     public int getMonitorInterval() {
429         return autoDeployService.getMonitorInterval();
430     }
431     
432     /**
433      * @param monitorInterval The monitorInterval to set (in secs).
434      */

435     public void setMonitorInterval(int monitorInterval) {
436         autoDeployService.setMonitorInterval(monitorInterval);
437     }
438
439     /**
440      * @return Returns the dumpStats.
441      */

442     public boolean isDumpStats() {
443         return environmentContext.isDumpStats();
444     }
445
446     /**
447      * @param value The dumpStats to set.
448      */

449     public void setDumpStats(boolean value) {
450         environmentContext.setDumpStats(value);
451     }
452
453     /**
454      * Install an component from a url
455      *
456      * @param url
457      * @throws DeploymentException
458      */

459     public void installArchive(String JavaDoc url) throws DeploymentException {
460         installationService.install(url, null, true);
461     }
462     
463     /**
464      * load an archive from an external location.
465      * The archive can be a Component, Service Assembly or Shared Library.
466      * @param location - can either be a url or filename (if relative - must be relative to the container)
467      * @param autoStart - if true will start the component/service assembly
468      * @throws DeploymentException
469      */

470     public void updateExternalArchive(String JavaDoc location,boolean autoStart) throws DeploymentException {
471         autoDeployService.updateExternalArchive(location, autoStart);
472     }
473     
474     /**
475      * load an archive from an external location and starts it
476      * The archive can be a Component, Service Assembly or Shared Library.
477      * @param location - can either be a url or filename (if relative - must be relative to the container)
478      * @throws DeploymentException
479      */

480     public void updateExternalArchive(String JavaDoc location) throws DeploymentException {
481         updateExternalArchive(location, true);
482     }
483     
484     
485     
486     
487
488     /**
489      * @return Returns the deploymentService.
490      */

491     public DeploymentService getDeploymentService() {
492         return deploymentService;
493     }
494
495     /**
496      * @return Returns the installationService.
497      */

498     public InstallationService getInstallationService() {
499         return installationService;
500     }
501
502     /**
503      * @return the AutomDeploymentService
504      */

505     public AutoDeploymentService getAutoDeploymentService() {
506         return autoDeployService;
507     }
508
509     /**
510      *
511      * @return the AdminCommandsService
512      */

513     public AdminCommandsService getAdminCommandsService() {
514         return adminCommandsService;
515     }
516     
517     public ClientFactory getClientFactory() {
518         return clientFactory;
519     }
520
521
522     /**
523      * light weight initialization - default values for mbeanSErver, TransactionManager etc are null
524      *
525      * @throws JBIException
526      */

527     public void init() throws JBIException {
528         if (containerInitialized.compareAndSet(false, true)) {
529             log.info("ServiceMix " +
530                      EnvironmentContext.getVersion() +
531                      " JBI Container (" + getName() + ") is starting");
532             log.info("For help or more informations please see: http://incubator.apache.org/servicemix/");
533             addShutdownHook();
534             if (this.workManager == null) {
535                 this.workManager = createWorkManager();
536                 this.isWorkManagerCreated = true;
537             }
538             if (this.namingContext == null) {
539                 try {
540                     this.namingContext = new InitialContext JavaDoc();
541                 }
542                 catch (NamingException JavaDoc e) {
543                     // Log a warning, with exception only in debug
544
if (log.isDebugEnabled()) {
545                         log.warn("Failed to set InitialContext", e);
546                     } else {
547                         log.warn("Failed to set InitialContext");
548                     }
549                 }
550             }
551             managementContext.init(this, getMBeanServer());
552             mbeanServer = this.managementContext.getMBeanServer();// just in case ManagementContext creates it
553
environmentContext.init(this, rootDir);
554             clientFactory.init(this);
555             registry.init(this);
556             broker.init(this);
557             installationService.init(this);
558             deploymentService.init(this);
559             autoDeployService.init(this);
560             adminCommandsService.init(this);
561
562             // register self with the ManagementContext
563
try {
564                 managementContext.registerMBean(ManagementContext.getContainerObjectName(managementContext.getJmxDomainName(), getName()),
565                                                 this, LifeCycleMBean.class);
566             } catch (JMException JavaDoc e) {
567                 throw new JBIException(e);
568             }
569             
570             // Initialize listeners after the whole container has been initialized
571
// so that they can register themselves as JMX mbeans for example
572
if (configuredListeners != null) {
573                 for (int i = 0; i < configuredListeners.length; i++) {
574                     EventListener JavaDoc listener = configuredListeners[i];
575                     addListener(listener);
576                 }
577             }
578         }
579     }
580
581     /**
582      * start processing
583      *
584      * @throws JBIException
585      */

586     public void start() throws JBIException {
587         checkInitialized();
588         if (started.compareAndSet(false, true)) {
589             managementContext.start();
590             environmentContext.start();
591             clientFactory.start();
592             registry.start();
593             broker.start();
594             installationService.start();
595             deploymentService.start();
596             autoDeployService.start();
597             adminCommandsService.start();
598             super.start();
599             log.info("ServiceMix JBI Container (" + getName() + ") started");
600         }
601     }
602
603     /**
604      * stop the container from processing
605      *
606      * @throws JBIException
607      */

608     public void stop() throws JBIException {
609         checkInitialized();
610         if (started.compareAndSet(true, false)) {
611             log.info("ServiceMix JBI Container (" + getName() + ") stopping");
612             adminCommandsService.stop();
613             autoDeployService.stop();
614             deploymentService.stop();
615             installationService.stop();
616             registry.stop();
617             broker.stop();
618             clientFactory.stop();
619             environmentContext.stop();
620             managementContext.stop();
621             super.stop();
622         }
623     }
624
625     /**
626      * After a shutdown the container will require an init before a start ...
627      *
628      * @throws JBIException
629      */

630     public void shutDown() throws JBIException {
631         if (containerInitialized.compareAndSet(true, false)) {
632             removeShutdownHook();
633             adminCommandsService.shutDown();
634             autoDeployService.shutDown();
635             deploymentService.shutDown();
636             installationService.shutDown();
637             // Shutdown broker before registry to avoid the JCA/JMS flow to send
638
// lots of messages when components and endpoints are stopped.
639
broker.shutDown();
640             registry.shutDown();
641             clientFactory.shutDown();
642             environmentContext.shutDown();
643             // shutdown the management context last, because it will close the mbean server
644
super.shutDown();
645             managementContext.unregisterMBean(this);
646             managementContext.shutDown();
647             if (isWorkManagerCreated && workManager instanceof GeronimoWorkManager) {
648                 try {
649                     ((GeronimoWorkManager) workManager).doStop();
650                 } catch (Exception JavaDoc e) {
651                     throw new JBIException("Could not stop workManager", e);
652                 }
653             }
654             log.info("ServiceMix JBI Container (" + getName() + ") stopped");
655         }
656     }
657
658     
659     protected void addShutdownHook() {
660         if (useShutdownHook) {
661             shutdownHook = new Thread JavaDoc("ServiceMix ShutdownHook") {
662                 public void run() {
663                     containerShutdown();
664                 }
665             };
666             Runtime.getRuntime().addShutdownHook(shutdownHook);
667         }
668     }
669
670     protected void removeShutdownHook() {
671         if (shutdownHook != null) {
672             try {
673                 Runtime.getRuntime().removeShutdownHook(shutdownHook);
674             }
675             catch (Exception JavaDoc e) {
676                 log.debug("Caught exception, must be shutting down: " + e);
677             }
678         }
679     }
680
681     /**
682      * Causes a clean shutdown of the container when the VM is being shut down
683      */

684     protected void containerShutdown() {
685         try {
686             shutDown();
687         }
688         catch (Exception JavaDoc e) {
689             System.err.println("Failed to shut down: " + e);
690         }
691     }
692
693     /**
694      * @return theMBean server assocated with the JBI
695      */

696     public synchronized MBeanServer JavaDoc getMBeanServer() {
697         return mbeanServer;
698     }
699
700     /**
701      * Set the MBeanServer
702      *
703      * @param mbs
704      */

705     public synchronized void setMBeanServer(MBeanServer JavaDoc mbs) {
706         this.mbeanServer = mbs;
707     }
708
709     /**
710      * @return the naming context
711      */

712     public synchronized InitialContext JavaDoc getNamingContext() {
713         return namingContext;
714     }
715
716     /**
717      * Set the naming context
718      *
719      * @param ic
720      */

721     public synchronized void setNamingContext(InitialContext JavaDoc ic) {
722         this.namingContext = ic;
723     }
724
725     /**
726      * @return the TransactionManager for this implementation
727      */

728     public synchronized Object JavaDoc getTransactionManager() {
729         if (transactionManager == null && namingContext != null) {
730             try {
731                 transactionManager = (TransactionManager JavaDoc) namingContext.lookup("java:appserver/TransactionManager");
732             }
733             catch (NamingException JavaDoc e) {
734                 log.debug("No transaction manager found from naming context: " + e.getMessage());
735                 try {
736                     transactionManager = (TransactionManager JavaDoc) namingContext.lookup("javax.transaction.TransactionManager");
737                 }
738                 catch (NamingException JavaDoc e1) {
739                     log.debug("No transaction manager found from naming context: " + e.getMessage());
740                 }
741             }
742         }
743         return transactionManager;
744     }
745
746     /**
747      * Set the transaction manager
748      *
749      * @param tm
750      */

751     public synchronized void setTransactionManager(Object JavaDoc tm) {
752         this.transactionManager = (TransactionManager JavaDoc) tm;
753     }
754
755     /**
756      * @return the root directory path
757      */

758     public synchronized String JavaDoc getRootDir() {
759         return this.rootDir;
760     }
761
762     /**
763      * Set the workspace root
764      *
765      * @param root
766      */

767     public synchronized void setRootDir(String JavaDoc root) {
768         this.rootDir = root;
769     }
770
771     /**
772      * @return Returns the workManager.
773      */

774     public WorkManager JavaDoc getWorkManager() {
775         return workManager;
776     }
777
778     /**
779      * @param workManager The workManager to set.
780      */

781     public void setWorkManager(WorkManager JavaDoc workManager) {
782         this.workManager = workManager;
783     }
784
785     /**
786      * Route an ExchangePacket to a destination
787      *
788      * @param exchange
789      * @throws MessagingException
790      */

791     public void sendExchange(MessageExchangeImpl exchange) throws MessagingException {
792         try {
793             broker.sendExchangePacket(exchange);
794         }
795         catch (MessagingException e) {
796             throw e;
797         }
798         catch (JBIException e) {
799             throw new MessagingException(e);
800         }
801     }
802     
803     
804     /**
805      * @param context
806      * @param externalEndpoint
807      * @throws JBIException
808      */

809     public void registerExternalEndpoint(ComponentNameSpace cns, ServiceEndpoint externalEndpoint)
810             throws JBIException {
811         registry.registerExternalEndpoint(cns, externalEndpoint);
812     }
813
814     /**
815      * @param context
816      * @param externalEndpoint
817      * @throws JBIException
818      */

819     public void deregisterExternalEndpoint(ComponentNameSpace cns, ServiceEndpoint externalEndpoint)
820             throws JBIException {
821         registry.deregisterExternalEndpoint(cns, externalEndpoint);
822     }
823
824     /**
825      * @param context
826      * @param epr
827      * @return matching endpoint or null
828      */

829     public ServiceEndpoint resolveEndpointReference(ComponentContextImpl context, DocumentFragment JavaDoc epr) {
830         return registry.resolveEndpointReference(epr);
831     }
832
833     /**
834      * @param context
835      * @param service
836      * @param name
837      * @return the matching endpoint
838      */

839     public ServiceEndpoint getEndpoint(ComponentContextImpl context, QName JavaDoc service, String JavaDoc name) {
840         return registry.getEndpoint(service, name);
841     }
842
843     /**
844      * @param context
845      * @param interfaceName
846      * @return endpoints that match the interface name
847      */

848     public ServiceEndpoint[] getEndpoints(ComponentContextImpl context, QName JavaDoc interfaceName) {
849         return registry.getEndpointsForInterface(interfaceName);
850     }
851
852     /**
853      * @param context
854      * @param serviceName
855      * @return endpoints for a given service
856      */

857     public ServiceEndpoint[] getEndpointsForService(ComponentContextImpl context, QName JavaDoc serviceName) {
858         return registry.getEndpointsForService(serviceName);
859     }
860
861     /**
862      * @param context
863      * @param interfaceName
864      * @return endpoints matching the interface name
865      */

866     public ServiceEndpoint[] getExternalEndpoints(ComponentContextImpl context, QName JavaDoc interfaceName) {
867         return registry.getExternalEndpoints(interfaceName);
868     }
869
870     /**
871      * @param context
872      * @param serviceName
873      * @return external endpoints
874      */

875     public ServiceEndpoint[] getExternalEndpointsForService(ComponentContextImpl context, QName JavaDoc serviceName) {
876         return registry.getExternalEndpointsForService(serviceName);
877     }
878
879     /**
880      * @param suffix
881      * @param resourceBundleName
882      * @return the Logger
883      * @throws MissingResourceException
884      * @throws JBIException
885      */

886     public Logger JavaDoc getLogger(String JavaDoc suffix, String JavaDoc resourceBundleName) throws MissingResourceException JavaDoc, JBIException {
887         try {
888             return Logger.getLogger(suffix, resourceBundleName);
889         } catch (IllegalArgumentException JavaDoc e) {
890             throw new JBIException("A logger can not be created using resource bundle " + resourceBundleName);
891         }
892     }
893
894     /**
895      * Used for Simple POJO's
896      *
897      * @param name - the unique component ID
898      * @throws JBIException
899      */

900     public void deactivateComponent(String JavaDoc name) throws JBIException {
901         ComponentMBeanImpl component = registry.getComponent(name);
902         if (component != null) {
903             component.doShutDown();
904             component.unregisterMbeans(managementContext);
905             registry.deregisterComponent(component);
906             environmentContext.unreregister(component);
907             log.info("Deactivating component " + name);
908         }
909         else {
910             throw new JBIException("Could not find component " + name);
911         }
912     }
913
914     /**
915      * Delete a Component
916      *
917      * @param id
918      * @throws JBIException
919      */

920     public void deleteComponent(String JavaDoc id) throws JBIException {
921         deactivateComponent(id);
922         environmentContext.removeComponentRootDirectory(id);
923     }
924
925     /**
926      * Get the component associated with the given component ID
927      *
928      * @param componentName
929      * @return the component
930      */

931     public ComponentMBeanImpl getComponent(String JavaDoc componentName) {
932         return registry.getComponent(componentName);
933     }
934
935     /**
936      * @return all local ComponentConnectors
937      */

938     public Collection JavaDoc getLocalComponentConnectors() {
939         return registry.getComponents();
940     }
941
942     /**
943      * Activates a new component
944      *
945      * @param activationSpec
946      * @return Component
947      * @throws JBIException
948      */

949     public Component activateComponent(ActivationSpec activationSpec) throws JBIException {
950         if (activationSpec.getId() == null) {
951             if (activationSpec.getComponentName() == null) {
952                 // lets generate one
953
activationSpec.setId(createComponentID());
954             } else {
955                 activationSpec.setId(activationSpec.getComponentName());
956             }
957         }
958         String JavaDoc id = activationSpec.getId();
959         if (id == null) {
960             throw new IllegalArgumentException JavaDoc("A Registration must have an ID");
961         }
962         if (activationSpec.getEndpoint() == null && activationSpec.getService() != null) {
963             // lets default to the ID
964
activationSpec.setEndpoint(id);
965         }
966         if (activationSpec.getComponentName() == null) {
967             activationSpec.setComponentName(id);
968         }
969         Object JavaDoc bean = activationSpec.getComponent();
970         if (bean == null) {
971             throw new IllegalArgumentException JavaDoc("A Registration must have a component associated with it");
972         }
973         if (bean instanceof Component) {
974             Component component = (Component) bean;
975             if (component instanceof ComponentSupport) {
976                 defaultComponentServiceAndEndpoint((ComponentSupport) component, activationSpec);
977             }
978             activateComponent(component, activationSpec);
979             return component;
980         }
981         else if (bean instanceof ComponentLifeCycle) {
982             // lets support just plain lifecycle pojos
983
ComponentLifeCycle lifeCycle = (ComponentLifeCycle) bean;
984             if (bean instanceof PojoSupport) {
985                 defaultComponentServiceAndEndpoint((PojoSupport) bean, activationSpec);
986             }
987             Component adaptor = createComponentAdaptor(lifeCycle, activationSpec);
988             activateComponent(adaptor, activationSpec);
989             return adaptor;
990         }
991         else if (bean instanceof MessageExchangeListener) {
992             // lets support just plain listener pojos
993
MessageExchangeListener listener = (MessageExchangeListener) bean;
994             Component adaptor = createComponentAdaptor(listener, activationSpec);
995             activateComponent(adaptor, activationSpec);
996             return adaptor;
997         }
998         else {
999             throw new IllegalArgumentException JavaDoc("Component name: " + id
1000                    + " is bound to an object which is not a JBI component, it is of type: "
1001                    + bean.getClass().getName());
1002        }
1003    }
1004
1005    /**
1006     * Activate a POJO Component
1007     *
1008     * @param component
1009     * @param name
1010     * @return the ObjectName of the MBean for the Component
1011     * @throws JBIException
1012     */

1013    public ObjectName JavaDoc activateComponent(Component component, String JavaDoc name) throws JBIException {
1014        ActivationSpec activationSpec = new ActivationSpec();
1015        ComponentNameSpace cns = new ComponentNameSpace(getName(), name);
1016        activationSpec.setComponent(component);
1017        activationSpec.setComponentName(cns.getName());
1018        return activateComponent(component, activationSpec);
1019    }
1020
1021    /**
1022     * Activate A POJO Component
1023     *
1024     * @param component
1025     * @param activationSpec
1026     * @return the ObjectName of the MBean for the Component
1027     * @throws JBIException
1028     */

1029    public ObjectName JavaDoc activateComponent(Component component, ActivationSpec activationSpec) throws JBIException {
1030        return activateComponent(component, "POJO Component", activationSpec, true, false, false, null);
1031    }
1032
1033    /**
1034     * Called by the Installer MBean
1035     *
1036     * @param installDir
1037     * @param component
1038     * @param description
1039     * @param context
1040     * @param binding
1041     * @param service
1042     * @return the ObjectName of the Component's MBean
1043     * @throws JBIException
1044     */

1045    public ObjectName JavaDoc activateComponent(File JavaDoc installDir, Component component, String JavaDoc description,
1046                                        ComponentContextImpl context, boolean binding, boolean service,
1047                                        String JavaDoc[] sharedLibraries) throws JBIException {
1048        ComponentNameSpace cns = context.getComponentNameSpace();
1049        ActivationSpec activationSpec = new ActivationSpec();
1050        activationSpec.setComponent(component);
1051        activationSpec.setComponentName(cns.getName());
1052        return activateComponent(installDir, component, description, context, activationSpec, false, binding, service, sharedLibraries);
1053    }
1054
1055    /**
1056     * @param component
1057     * @param description
1058     * @param activationSpec
1059     * @param pojo
1060     * @param binding
1061     * @param service
1062     * @return the ObjectName of the Component's MBean
1063     * @throws JBIException
1064     */

1065    public ObjectName JavaDoc activateComponent(Component component, String JavaDoc description, ActivationSpec activationSpec,
1066                                        boolean pojo, boolean binding, boolean service,
1067                                        String JavaDoc[] sharedLibraries) throws JBIException {
1068        ComponentNameSpace cns = new ComponentNameSpace(getName(), activationSpec.getComponentName());
1069        if (registry.getComponent(cns) != null) {
1070            throw new JBIException("A component is already registered for " + cns);
1071        }
1072        ComponentContextImpl context = new ComponentContextImpl(this, cns);
1073        return activateComponent(new File JavaDoc("."), component, description, context, activationSpec, pojo, binding, service, sharedLibraries);
1074    }
1075
1076    /**
1077     * @param installationDir
1078     * @param component
1079     * @param description
1080     * @param context
1081     * @param activationSpec
1082     * @param pojo
1083     * @param binding
1084     * @param service
1085     * @return the ObjectName of the Component's MBean
1086     * @throws JBIException
1087     */

1088    public ObjectName JavaDoc activateComponent(File JavaDoc installationDir, Component component, String JavaDoc description,
1089                                        ComponentContextImpl context, ActivationSpec activationSpec,
1090                                        boolean pojo, boolean binding, boolean service,
1091                                        String JavaDoc[] sharedLibraries)
1092            throws JBIException {
1093        ObjectName JavaDoc result = null;
1094        ComponentNameSpace cns = new ComponentNameSpace(getName(), activationSpec.getComponentName());
1095        if (log.isDebugEnabled()) {
1096            log.info("Activating component for: " + cns + " with service: " + activationSpec.getService() + " component: "
1097                    + component);
1098        }
1099        ComponentMBeanImpl lcc = registry.registerComponent(cns, description, component, binding, service, sharedLibraries);
1100        if (lcc != null) {
1101            lcc.setPojo(pojo);
1102            ComponentEnvironment env = environmentContext.registerComponent(context.getEnvironment(),lcc);
1103            if (env.getInstallRoot() == null) {
1104                env.setInstallRoot(installationDir);
1105            }
1106            context.activate(component, env, activationSpec);
1107            lcc.setContext(context);
1108            lcc.setActivationSpec(activationSpec);
1109            
1110            if (lcc.isPojo()) {
1111                //non-pojo's are either started by the auto deployer
1112
//or manually
1113
lcc.init();
1114            } else {
1115                lcc.doShutDown();
1116            }
1117            result = lcc.registerMBeans(managementContext);
1118            // Start the component after mbeans have been registered
1119
// This can be usefull if listeners use them
1120
if (lcc.isPojo() && started.get()) {
1121                lcc.start();
1122            }
1123        }
1124        return result;
1125    }
1126
1127    /**
1128     * Allow the service and endpoint name to be configured from the registration, to reduce the amount of XML which is
1129     * required to configure a ServiceMix component
1130     *
1131     * @param component
1132     * @param activationSpec
1133     */

1134    protected void defaultComponentServiceAndEndpoint(PojoSupport component, ActivationSpec activationSpec) {
1135        if (activationSpec.getService() != null) {
1136            component.setService(activationSpec.getService());
1137        }
1138        if (activationSpec.getEndpoint() != null) {
1139            component.setEndpoint(activationSpec.getEndpoint());
1140        }
1141    }
1142
1143    /**
1144     * Factory method to create a new work manager instance
1145     *
1146     * @return a newly created work manager
1147     */

1148    protected WorkManager JavaDoc createWorkManager() throws JBIException {
1149        WorkManagerFactoryBean factory = new WorkManagerFactoryBean();
1150        try {
1151            return factory.getWorkManager();
1152        }
1153        catch (Exception JavaDoc e) {
1154            throw new JBIException("Failed to start WorkManager: " + e, e);
1155        }
1156    }
1157
1158
1159    /**
1160     * Factory method to create a new component adaptor from the given lifecycle
1161     *
1162     * @param lifeCycle
1163     * @param activationSpec
1164     * @return Component
1165     */

1166    protected Component createComponentAdaptor(ComponentLifeCycle lifeCycle, ActivationSpec activationSpec) {
1167        ComponentAdaptor answer = null;
1168        if (lifeCycle instanceof MessageExchangeListener) {
1169            answer = new ComponentAdaptorMEListener(lifeCycle, activationSpec.getService(), activationSpec
1170                    .getEndpoint(), (MessageExchangeListener) lifeCycle);
1171        }
1172        else {
1173            answer = new ComponentAdaptor(lifeCycle, activationSpec.getService(), activationSpec.getEndpoint());
1174        }
1175        answer.setServiceManager(serviceManager);
1176        return answer;
1177    }
1178
1179    protected Component createComponentAdaptor(MessageExchangeListener listener, ActivationSpec activationSpec) {
1180        ComponentLifeCycle lifecCycle = new PojoLifecycleAdaptor(listener, activationSpec.getService(), activationSpec
1181                .getEndpoint());
1182        return new ComponentAdaptorMEListener(lifecCycle, listener);
1183    }
1184
1185    /**
1186     * Factory method to create a new component ID if none is specified
1187     *
1188     * @return uniqueId
1189     */

1190    protected String JavaDoc createComponentID() {
1191        return idGenerator.generateId();
1192    }
1193
1194    protected void checkInitialized() throws JBIException {
1195        if (containerInitialized.get() == false) {
1196            throw new JBIException("The Container is not initialized - please call init(...)");
1197        }
1198    }
1199
1200    /**
1201     * Retrieve the value for automatic transaction enlistment.
1202     * @return
1203     */

1204    public boolean isAutoEnlistInTransaction() {
1205        return autoEnlistInTransaction;
1206    }
1207
1208    /**
1209     * Set the new value for automatic transaction enlistment.
1210     * When this parameter is set to <code>true</code> and a transaction
1211     * is running when sending / receiving an exchange, this operation will
1212     * automatically be done in the current transaction.
1213     *
1214     * @param autoEnlistInTransaction
1215     */

1216    public void setAutoEnlistInTransaction(boolean autoEnlistInTransaction) {
1217        this.autoEnlistInTransaction = autoEnlistInTransaction;
1218    }
1219
1220    public boolean isPersistent() {
1221        return persistent;
1222    }
1223
1224    /**
1225     * Set the new default value for exchange persistence.
1226     * This value will be the default if none is configured on
1227     * the activation spec of the component or on the message.
1228     *
1229     * @param persistent
1230     */

1231    public void setPersistent(boolean persistent) {
1232        this.persistent = persistent;
1233    }
1234    
1235    public void addListener(EventListener JavaDoc listener) {
1236        if (listener instanceof ContainerAware) {
1237            ContainerAware containerAware = (ContainerAware) listener;
1238            containerAware.setContainer(this);
1239        }
1240        if (listener instanceof ExchangeListener) {
1241            listeners.add(ExchangeListener.class, (ExchangeListener) listener);
1242        }
1243        if (listener instanceof ComponentListener) {
1244            listeners.add(ComponentListener.class, (ComponentListener) listener);
1245        }
1246        if (listener instanceof ServiceAssemblyListener) {
1247            listeners.add(ServiceAssemblyListener.class, (ServiceAssemblyListener) listener);
1248        }
1249        if (listener instanceof ServiceUnitListener) {
1250            listeners.add(ServiceUnitListener.class, (ServiceUnitListener) listener);
1251        }
1252        if (listener instanceof EndpointListener) {
1253            listeners.add(EndpointListener.class, (EndpointListener) listener);
1254        }
1255    }
1256    
1257    public void removeListener(EventListener JavaDoc listener) {
1258        if (listener instanceof ExchangeListener) {
1259            listeners.remove(ExchangeListener.class, (ExchangeListener) listener);
1260        }
1261        if (listener instanceof ComponentListener) {
1262            listeners.remove(ComponentListener.class, (ComponentListener) listener);
1263        }
1264        if (listener instanceof ServiceAssemblyListener) {
1265            listeners.remove(ServiceAssemblyListener.class, (ServiceAssemblyListener) listener);
1266        }
1267        if (listener instanceof ServiceUnitListener) {
1268            listeners.remove(ServiceUnitListener.class, (ServiceUnitListener) listener);
1269        }
1270        if (listener instanceof EndpointListener) {
1271            listeners.remove(EndpointListener.class, (EndpointListener) listener);
1272        }
1273    }
1274    
1275    public Object JavaDoc[] getListeners(Class JavaDoc lc) {
1276        return listeners.getListeners(lc);
1277    }
1278    
1279    public void setListeners(EventListener JavaDoc[] listeners) {
1280        configuredListeners = listeners;
1281    }
1282    
1283    public void callListeners(MessageExchange exchange) {
1284        ExchangeListener[] l = (ExchangeListener[]) listeners.getListeners(ExchangeListener.class);
1285        ExchangeEvent event = new ExchangeEvent(exchange);
1286        for (int i = 0; i < l.length; i++) {
1287            try {
1288                l[i].exchangeSent(event);
1289            } catch (Exception JavaDoc e) {
1290                log.warn("Error calling listener: " + e.getMessage(), e);
1291            }
1292        }
1293    }
1294
1295    public void resendExchange(MessageExchange exchange) throws JBIException {
1296        if (exchange instanceof MessageExchangeImpl == false) {
1297            throw new IllegalArgumentException JavaDoc("exchange should be a MessageExchangeImpl");
1298        }
1299        MessageExchangeImpl me = (MessageExchangeImpl) exchange;
1300        me.getPacket().setExchangeId(new IdGenerator().generateId());
1301        me.getPacket().setOut(null);
1302        me.getPacket().setFault(null);
1303        me.getPacket().setError(null);
1304        me.getPacket().setStatus(ExchangeStatus.ACTIVE);
1305        me.getPacket().setProperty(JbiConstants.DATESTAMP_PROPERTY_NAME, Calendar.getInstance());
1306        callListeners(me);
1307        me.handleSend(false);
1308        sendExchange(me.getMirror());
1309    }
1310
1311    public boolean isEmbedded() {
1312        return embedded;
1313    }
1314
1315    public void setEmbedded(boolean embedded) {
1316        this.embedded = embedded;
1317    }
1318    
1319    public void setRmiPort( int portNum ) {
1320        getManagementContext().setNamingPort( portNum );
1321    }
1322
1323    public int getRmiPort() {
1324        return getManagementContext().getNamingPort();
1325    }
1326
1327    /**
1328     * @return Returns the notifyStatistics.
1329     */

1330    public boolean isNotifyStatistics() {
1331        return notifyStatistics;
1332    }
1333
1334    /**
1335     * @param notifyStatistics The notifyStatistics to set.
1336     */

1337    public void setNotifyStatistics(boolean notifyStatistics) {
1338        this.notifyStatistics = notifyStatistics;
1339    }
1340}
1341
Popular Tags