KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > framework > ComponentMBeanImpl


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.framework;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.Properties JavaDoc;
22
23 import javax.jbi.JBIException;
24 import javax.jbi.component.Component;
25 import javax.jbi.component.ComponentLifeCycle;
26 import javax.jbi.component.ServiceUnitManager;
27 import javax.jbi.management.DeploymentException;
28 import javax.jbi.management.LifeCycleMBean;
29 import javax.management.JMException JavaDoc;
30 import javax.management.MBeanAttributeInfo JavaDoc;
31 import javax.management.MBeanOperationInfo JavaDoc;
32 import javax.management.ObjectName JavaDoc;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.apache.servicemix.jbi.container.ActivationSpec;
37 import org.apache.servicemix.jbi.container.JBIContainer;
38 import org.apache.servicemix.jbi.event.ComponentEvent;
39 import org.apache.servicemix.jbi.event.ComponentListener;
40 import org.apache.servicemix.jbi.management.AttributeInfoHelper;
41 import org.apache.servicemix.jbi.management.BaseLifeCycle;
42 import org.apache.servicemix.jbi.management.ManagementContext;
43 import org.apache.servicemix.jbi.management.OperationInfoHelper;
44 import org.apache.servicemix.jbi.messaging.DeliveryChannelImpl;
45 import org.apache.servicemix.jbi.messaging.MessagingStats;
46 import org.apache.servicemix.jbi.util.XmlPersistenceSupport;
47
48 /**
49  * Defines basic statistics on the Component
50  */

51 public class ComponentMBeanImpl extends BaseLifeCycle implements ComponentMBean {
52     
53     private static Log log = LogFactory.getLog(ComponentMBeanImpl.class);
54     
55     private boolean exchangeThrottling;
56     private long throttlingTimeout = 100;
57     private int throttlingInterval = 1;
58        
59     private Component component;
60     private ComponentLifeCycle lifeCycle;
61     private ServiceUnitManager suManager;
62     private ComponentContextImpl context;
63     private ActivationSpec activationSpec;
64     private ObjectName JavaDoc mBeanName;
65     private ComponentStats componentStatsMBean;
66     private ObjectName JavaDoc componentStatsMBeanName;
67     private JBIContainer container;
68     private MessagingStats messagingStats;
69     private ComponentNameSpace componentName;
70     private String JavaDoc description = "POJO Component";
71     private boolean pojo;
72     private boolean binding;
73     private boolean service;
74     private File JavaDoc stateFile;
75     private String JavaDoc[] sharedLibraries;
76
77     /**
78      * Construct with it's id and delivery channel Id
79      *
80      * @param name
81      * @param description
82      * @param component
83      * @param dc
84      * @param binding
85      * @param service
86      */

87     public ComponentMBeanImpl(JBIContainer container,
88                               ComponentNameSpace name,
89                               String JavaDoc description,
90                               Component component,
91                               boolean binding,
92                               boolean service,
93                               String JavaDoc[] sharedLibraries) {
94         this.componentName = name;
95         this.container = container;
96         this.component = component;
97         this.description = description;
98         this.binding = binding;
99         this.service = service;
100         this.componentStatsMBean = new ComponentStats(this);
101         this.messagingStats = new MessagingStats(name.getName());
102         this.sharedLibraries = sharedLibraries;
103     }
104
105     /**
106      * Register the MBeans for this Component
107      * @param context
108      * @return ObjectName
109      * @throws JBIException
110      */

111     public ObjectName JavaDoc registerMBeans(ManagementContext context) throws JBIException{
112         try{
113             mBeanName = context.createObjectName(this);
114             context.registerMBean(mBeanName, this, ComponentMBean.class);
115             componentStatsMBeanName = context.createObjectName(componentStatsMBean);
116             context.registerMBean(componentStatsMBeanName, componentStatsMBean, ComponentStatsMBean.class);
117             return mBeanName;
118         }catch(Exception JavaDoc e){
119             String JavaDoc errorStr="Failed to register MBeans";
120             log.error(errorStr,e);
121             throw new JBIException(errorStr,e);
122         }
123     }
124     
125     /**
126      * Unregister Component MBeans
127      * @param context
128      * @throws JBIException
129      */

130     public void unregisterMbeans(ManagementContext context) throws JBIException{
131         context.unregisterMBean(mBeanName);
132         context.unregisterMBean(componentStatsMBeanName);
133     }
134
135     /**
136      * Set the Context
137      *
138      * @param context
139      */

140     public void setContext(ComponentContextImpl context) {
141         this.context = context;
142         this.stateFile = context.getEnvironment().getStateFile();
143     }
144
145     /**
146      * Get the JMX ObjectName for any additional MBean for this component. If there is none, return null.
147      *
148      * @return ObjectName the JMX object name of the additional MBean or null if there is no additional MBean.
149      */

150     public ObjectName JavaDoc getExtensionMBeanName() {
151         if (isInitialized() || isStarted() || isStopped()) {
152             return lifeCycle.getExtensionMBeanName();
153         } else {
154             return null;
155         }
156     }
157     
158     /**
159      * Get the name of the item
160      * @return the name
161      */

162     public String JavaDoc getName() {
163         return componentName.getName();
164     }
165     
166     /**
167      * Get the type of the item
168      * @return the type
169      */

170     public String JavaDoc getType() {
171         return "Component";
172     }
173     
174     public String JavaDoc getSubType() {
175         return "LifeCycle";
176     }
177     
178    /**
179      * Get the Description of the item
180      * @return the description
181      */

182     public String JavaDoc getDescription(){
183         return description;
184     }
185
186     
187     public void init() throws JBIException {
188         log.info("Initializing component: " + getName());
189         if (context != null && component != null) {
190             DeliveryChannelImpl channel = new DeliveryChannelImpl(this);
191             channel.setContext(context);
192             context.setDeliveryChannel(channel);
193             ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
194             try {
195                 Thread.currentThread().setContextClassLoader(getLifeCycle().getClass().getClassLoader());
196                 getLifeCycle().init(context);
197             } finally {
198                 Thread.currentThread().setContextClassLoader(loader);
199             }
200         }
201         super.init();
202     }
203     
204     /**
205      * Start the item.
206      *
207      * @exception javax.jbi.JBIException if the item fails to start.
208      */

209     public void start() throws javax.jbi.JBIException {
210         log.info("Starting component: " + getName());
211         try {
212             doStart();
213             persistRunningState();
214             getContainer().getRegistry().checkPendingAssemblies();
215         } catch (JBIException e) {
216             log.error("Could not start component", e);
217             throw e;
218         } catch (RuntimeException JavaDoc e) {
219             log.error("Could not start component", e);
220             throw e;
221         } catch (Error JavaDoc e) {
222             log.error("Could not start component", e);
223             throw e;
224         }
225     }
226
227     /**
228      * Stop the item. This suspends current messaging activities.
229      *
230      * @exception javax.jbi.JBIException if the item fails to stop.
231      */

232     public void stop() throws javax.jbi.JBIException {
233         log.info("Stopping component: " + getName());
234         try {
235             doStop();
236             persistRunningState();
237         } catch (JBIException e) {
238             log.error("Could not stop component", e);
239             throw e;
240         } catch (RuntimeException JavaDoc e) {
241             log.error("Could not start component", e);
242             throw e;
243         } catch (Error JavaDoc e) {
244             log.error("Could not start component", e);
245             throw e;
246         }
247     }
248
249     /**
250      * Shut down the item. The releases resources, preparatory to uninstallation.
251      *
252      * @exception javax.jbi.JBIException if the item fails to shut down.
253      */

254     public void shutDown() throws javax.jbi.JBIException {
255         log.info("Shutting down component: " + getName());
256         try {
257             doShutDown();
258             persistRunningState();
259         } catch (JBIException e) {
260             log.error("Could not shutDown component", e);
261             throw e;
262         } catch (RuntimeException JavaDoc e) {
263             log.error("Could not start component", e);
264             throw e;
265         } catch (Error JavaDoc e) {
266             log.error("Could not start component", e);
267             throw e;
268         }
269     }
270     
271     public void setShutdownStateAfterInstall() {
272         setCurrentState(SHUTDOWN);
273     }
274     
275     /**
276      * Start the item - doesn't persist the state
277      *
278      * @exception javax.jbi.JBIException if the item fails to start.
279      */

280     public void doStart() throws javax.jbi.JBIException {
281         if (isShutDown()) {
282             // need to re-initialze before starting
283
init();
284         }
285         if (!isStarted()) {
286             ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
287             try {
288                 Thread.currentThread().setContextClassLoader(getLifeCycle().getClass().getClassLoader());
289                 getLifeCycle().start();
290             } finally {
291                 Thread.currentThread().setContextClassLoader(loader);
292             }
293             super.start();
294             initServiceAssemblies();
295             startServiceAssemblies();
296         }
297         fireEvent(ComponentEvent.COMPONENT_STARTED);
298     }
299
300     /**
301      * Stop the item - doesn't persist the state
302      *
303      * @exception javax.jbi.JBIException
304      * if the item fails to stop.
305      */

306     public void doStop() throws javax.jbi.JBIException {
307         if (isUnknown() || isStarted()) {
308             stopServiceAssemblies();
309             ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
310             try {
311                 Thread.currentThread().setContextClassLoader(getLifeCycle().getClass().getClassLoader());
312                 getLifeCycle().stop();
313             } finally {
314                 Thread.currentThread().setContextClassLoader(loader);
315             }
316             super.stop();
317         }
318         fireEvent(ComponentEvent.COMPONENT_STOPPED);
319     }
320
321     /**
322      * Shut down the item - doesn't persist the state
323      *
324      * @exception javax.jbi.JBIException if the item fails to shut down.
325      */

326     public void doShutDown() throws javax.jbi.JBIException {
327         // Transition from UNKNOWN to SHUTDOWN is done at installation time
328
// In this case or if the component is already shut down, do nothing
329
if (!isUnknown() && !isShutDown()) {
330             doStop();
331             shutDownServiceAssemblies();
332             ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
333             try {
334                 Thread.currentThread().setContextClassLoader(getLifeCycle().getClass().getClassLoader());
335                 getLifeCycle().shutDown();
336             } finally {
337                 Thread.currentThread().setContextClassLoader(loader);
338             }
339             if (getDeliveryChannel() != null) {
340                 getDeliveryChannel().close();
341                 setDeliveryChannel(null);
342             }
343         }
344         super.shutDown();
345         fireEvent(ComponentEvent.COMPONENT_SHUTDOWN);
346     }
347     
348     
349     /**
350      * Set the initial running state of the Component
351      * @throws JBIException
352      */

353     public void setInitialRunningState() throws JBIException{
354         if (!isPojo()) {
355             String JavaDoc componentName = getName();
356             String JavaDoc runningState = getRunningStateFromStore();
357             log.info("Setting running state for Component: " + componentName + " to " + runningState);
358             if (runningState != null) {
359                 if (runningState.equals(LifeCycleMBean.STARTED)) {
360                     doStart();
361                 } else if (runningState.equals(LifeCycleMBean.STOPPED)) {
362                     doStart();
363                     doStop();
364                 } else if (runningState.equals(LifeCycleMBean.SHUTDOWN)) {
365                     doShutDown();
366                 }
367             }
368         }
369     }
370     
371     /**
372      * Persist the running state
373      */

374     public void persistRunningState() {
375         if (!isPojo()) {
376             String JavaDoc componentName = getName();
377             try {
378                 String JavaDoc currentState = getCurrentState();
379                 Properties JavaDoc props = new Properties JavaDoc();
380                 props.setProperty("state", currentState);
381                 XmlPersistenceSupport.write(stateFile, props);
382             } catch (IOException JavaDoc e) {
383                 log.error("Failed to write current running state for Component: " + componentName, e);
384             }
385         }
386     }
387    
388     /**
389      * @return the current running state from disk
390      */

391     public String JavaDoc getRunningStateFromStore() {
392         String JavaDoc result = LifeCycleMBean.UNKNOWN;
393         String JavaDoc componentName = getName();
394         try {
395             Properties JavaDoc props = (Properties JavaDoc) XmlPersistenceSupport.read(stateFile);
396             result = props.getProperty("state", result);
397         } catch (Exception JavaDoc e) {
398             log.error("Failed to read running state for Component: " + componentName, e);
399         }
400         return result;
401     }
402
403     /**
404      * @return the capacity of the inbound queue
405      */

406     public int getInboundQueueCapacity(){
407         // TODO: should not be on the delivery channel
408
if (getDeliveryChannel() != null) {
409             return getDeliveryChannel().getQueueCapacity();
410         } else {
411             return 0;
412         }
413     }
414     
415     /**
416      * Set the inbound queue capacity
417      * @param value
418      */

419     public void setInboundQueueCapacity(int value){
420         // TODO: should not be on the delivery channel
421
if (getDeliveryChannel() != null) {
422             getDeliveryChannel().setQueueCapacity(value);
423         }
424     }
425     
426     /**
427      * @return Returns the deliveryChannel.
428      */

429     public DeliveryChannelImpl getDeliveryChannel() {
430         return (DeliveryChannelImpl) context.getDeliveryChannel();
431     }
432
433     /**
434      * @param deliveryChannel
435      * The deliveryChannel to set.
436      */

437     public void setDeliveryChannel(DeliveryChannelImpl deliveryChannel) {
438         context.setDeliveryChannel(deliveryChannel);
439     }
440
441     /**
442      * @return the ActivateionSpec
443      */

444     public ActivationSpec getActivationSpec() {
445         return activationSpec;
446     }
447
448     /**
449      * @return Returns the pojo.
450      */

451     public boolean isPojo() {
452         return pojo;
453     }
454
455     /**
456      * Set the ActivationSpec
457      *
458      * @param activationSpec
459      */

460     public void setActivationSpec(ActivationSpec activationSpec) {
461         this.activationSpec = activationSpec;
462     }
463
464     /**
465      * Is MessageExchange sender throttling enabled ?
466      *
467      * @return true if throttling enabled
468      */

469     public boolean isExchangeThrottling() {
470         return exchangeThrottling;
471     }
472
473     /**
474      * Set message throttling
475      *
476      * @param value
477      */

478     public void setExchangeThrottling(boolean value) {
479         this.exchangeThrottling = value;
480     }
481
482     /**
483      * Get the throttling timeout
484      *
485      * @return throttling tomeout (ms)
486      */

487     public long getThrottlingTimeout() {
488         return throttlingTimeout;
489     }
490
491     /**
492      * Set the throttling timout
493      *
494      * @param value (ms)
495      */

496     public void setThrottlingTimeout(long value) {
497         throttlingTimeout = value;
498     }
499
500     /**
501      * Get the interval for throttling - number of Exchanges set before the throttling timeout is applied
502      *
503      * @return interval for throttling
504      */

505     public int getThrottlingInterval() {
506         return throttlingInterval;
507     }
508
509     /**
510      * Set the throttling interval number of Exchanges set before the throttling timeout is applied
511      *
512      * @param value
513      */

514     public void setThrottlingInterval(int value) {
515         throttlingInterval = value;
516     }
517
518     /**
519      * @return the ObjectName for the stats MBean for this Component - or null if it doesn't exist
520      */

521     public ObjectName JavaDoc getStatsMBeanName(){
522         return componentStatsMBeanName;
523     }
524     /**
525      * Get an array of MBeanAttributeInfo
526      *
527      * @return array of AttributeInfos
528      * @throws JMException
529      */

530     public MBeanAttributeInfo JavaDoc[] getAttributeInfos() throws JMException JavaDoc {
531         AttributeInfoHelper helper = new AttributeInfoHelper();
532         helper.addAttribute(getObjectToManage(), "inboundQueueCapacity", "capacity of the inbound queue");
533         helper.addAttribute(getObjectToManage(), "exchangeThrottling", "apply throttling");
534         helper.addAttribute(getObjectToManage(), "throttlingTimeout", "timeout for throttling");
535         helper.addAttribute(getObjectToManage(), "throttlingInterval", "exchange intervals before throttling");
536         helper.addAttribute(getObjectToManage(), "extensionMBeanName", "extension mbean name");
537         helper.addAttribute(getObjectToManage(), "statsMBeanName", "Statistics mbean name");
538         return AttributeInfoHelper.join(super.getAttributeInfos(), helper.getAttributeInfos());
539     }
540
541     /**
542      * Get an array of MBeanOperationInfo
543      *
544      * @return array of OperationInfos
545      * @throws JMException
546      */

547     public MBeanOperationInfo JavaDoc[] getOperationInfos() throws JMException JavaDoc {
548         OperationInfoHelper helper = new OperationInfoHelper();
549         return OperationInfoHelper.join(super.getOperationInfos(), helper.getOperationInfos());
550     }
551
552     public void firePropertyChanged(String JavaDoc name, Object JavaDoc oldValue, Object JavaDoc newValue) {
553         super.firePropertyChanged(name, oldValue, newValue);
554     }
555
556     protected void initServiceAssemblies() throws DeploymentException {
557     }
558
559     protected void startServiceAssemblies() throws DeploymentException {
560     }
561
562     protected void stopServiceAssemblies() throws DeploymentException {
563         Registry registry = getContainer().getRegistry();
564         String JavaDoc[] sas = registry.getDeployedServiceAssembliesForComponent(getName());
565         for (int i = 0; i < sas.length; i++) {
566             ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(sas[i]);
567             if (sa.isStarted()) {
568                 try {
569                     sa.stop(false, false);
570                     registry.addPendingAssembly(sa);
571                 } catch (Exception JavaDoc e) {
572                     log.error("Error stopping service assembly " + sas[i]);
573                 }
574             }
575         }
576     }
577
578     protected void shutDownServiceAssemblies() throws DeploymentException {
579         Registry registry = getContainer().getRegistry();
580         String JavaDoc[] sas = registry.getDeployedServiceAssembliesForComponent(getName());
581         for (int i = 0; i < sas.length; i++) {
582             ServiceAssemblyLifeCycle sa = registry.getServiceAssembly(sas[i]);
583             if (sa.isStopped()) {
584                 try {
585                     sa.shutDown(false);
586                     registry.addPendingAssembly(sa);
587                 } catch (Exception JavaDoc e) {
588                     log.error("Error shutting down service assembly " + sas[i]);
589                 }
590             }
591         }
592     }
593     
594     protected void fireEvent(int type) {
595         ComponentEvent event = new ComponentEvent(this, type);
596         ComponentListener[] listeners = (ComponentListener[]) getContainer().getListeners(ComponentListener.class);
597         for (int i = 0; i < listeners.length; i++) {
598             switch (type) {
599             case ComponentEvent.COMPONENT_STARTED:
600                 listeners[i].componentStarted(event);
601                 break;
602             case ComponentEvent.COMPONENT_STOPPED:
603                 listeners[i].componentStopped(event);
604                 break;
605             case ComponentEvent.COMPONENT_SHUTDOWN:
606                 listeners[i].componentShutDown(event);
607                 break;
608             }
609         }
610         
611     }
612
613     public ComponentLifeCycle getLifeCycle() {
614         if (lifeCycle == null) {
615             lifeCycle = component.getLifeCycle();
616         }
617         return lifeCycle;
618     }
619
620     public ServiceUnitManager getServiceUnitManager() {
621         if (suManager == null) {
622             suManager = component.getServiceUnitManager();
623         }
624         return suManager;
625     }
626
627     public JBIContainer getContainer() {
628         return container;
629     }
630
631     /**
632      * @return Returns the messagingStats.
633      */

634     public MessagingStats getMessagingStats() {
635         return messagingStats;
636     }
637
638     public Component getComponent() {
639         return component;
640     }
641     
642     public ComponentNameSpace getComponentNameSpace() {
643         return componentName;
644     }
645
646     public ComponentContextImpl getContext() {
647         return context;
648     }
649     public ObjectName JavaDoc getMBeanName() {
650         return mBeanName;
651     }
652     public boolean isBinding() {
653         return binding;
654     }
655     public boolean isService() {
656         return service;
657     }
658
659     public void setPojo(boolean pojo) {
660         this.pojo = pojo;
661     }
662
663     public boolean isEngine() {
664         return service;
665     }
666
667     /**
668      * @return the sharedLibraries
669      */

670     public String JavaDoc[] getSharedLibraries() {
671         return sharedLibraries;
672     }
673
674 }
675
Popular Tags