KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > management > ManagementContext


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.management;
18
19 import java.io.IOException JavaDoc;
20 import java.util.Collection JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.LinkedHashMap JavaDoc;
23 import java.util.Map JavaDoc;
24 import javax.jbi.JBIException;
25 import javax.management.JMException JavaDoc;
26 import javax.management.MBeanAttributeInfo JavaDoc;
27 import javax.management.MBeanOperationInfo JavaDoc;
28 import javax.management.MBeanServer JavaDoc;
29 import javax.management.MalformedObjectNameException JavaDoc;
30 import javax.management.ObjectName JavaDoc;
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.servicemix.jbi.container.EnvironmentContext;
34 import org.apache.servicemix.jbi.container.JBIContainer;
35 import org.apache.servicemix.jbi.framework.ComponentMBeanImpl;
36 import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
37 import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService;
38 import edu.emory.mathcs.backport.java.util.concurrent.Executors;
39
40 /**
41  * Management Context applied to a ServiceMix container
42  *
43  * @version $Revision: 440289 $
44  */

45 public class ManagementContext extends BaseSystemService implements ManagementContextMBean {
46     /**
47      * Default servicemix domain
48      */

49     public static final String JavaDoc DEFAULT_DOMAIN = "org.apache.servicemix";
50     public static final String JavaDoc DEFAULT_CONNECTOR_PATH = "/jmxrmi";
51     public static final int DEFAULT_CONNECTOR_PORT = 1099;
52     private final static Log log = LogFactory.getLog(ManagementContext.class);
53     private Map JavaDoc beanMap = new ConcurrentHashMap();
54     protected Map JavaDoc systemServices = new ConcurrentHashMap();
55     private MBeanServerContext mbeanServerContext = new MBeanServerContext();
56     private ExecutorService executors;
57
58     /**
59      * Default Constructor
60      */

61     public ManagementContext() {
62         mbeanServerContext.setJmxDomainName(DEFAULT_DOMAIN);
63     }
64
65     /**
66      * Get the Description of the item
67      *
68      * @return the description
69      */

70     public String JavaDoc getDescription() {
71         return "JMX Management";
72     }
73
74     
75
76     /**
77      * Get the MBeanServer
78      *
79      * @return the MBeanServer
80      */

81     public MBeanServer JavaDoc getMBeanServer() {
82         return mbeanServerContext.getMBeanServer();
83     }
84     
85     /**
86      * @return the domain
87      */

88     public String JavaDoc getJmxDomainName(){
89         return mbeanServerContext.getJmxDomainName();
90     }
91
92     
93    
94     /**
95      * @return Returns the useMBeanServer.
96      */

97     public boolean isUseMBeanServer() {
98         return mbeanServerContext.isUseMBeanServer();
99     }
100
101     /**
102      * @param useMBeanServer The useMBeanServer to set.
103      */

104     public void setUseMBeanServer(boolean useMBeanServer) {
105         mbeanServerContext.setUseMBeanServer(useMBeanServer);
106     }
107     
108     /**
109      * @return Returns the createMBeanServer flag.
110      */

111     public boolean isCreateMBeanServer() {
112         return mbeanServerContext.isCreateMBeanServer();
113     }
114
115     /**
116      * @param enableJMX Set createMBeanServer.
117      */

118     public void setCreateMBeanServer(boolean enableJMX) {
119         mbeanServerContext.setCreateMBeanServer(enableJMX);
120     }
121     
122     public void setNamingPort(int portNum) {
123         mbeanServerContext.setConnectorPort(portNum);
124     }
125
126     public int getNamingPort() {
127         return mbeanServerContext.getConnectorPort();
128     }
129     
130     public boolean isCreateJmxConnector() {
131         return mbeanServerContext.isCreateConnector();
132     }
133     
134     public void setCreateJmxConnector(boolean createJmxConnector) {
135         mbeanServerContext.setCreateConnector(createJmxConnector);
136     }
137
138     /**
139      * Initialize the ManagementContext
140      *
141      * @param container
142      * @param server
143      * @throws JBIException
144     
145      */

146     public void init(JBIContainer container, MBeanServer JavaDoc server) throws JBIException {
147         if (container.isEmbedded() && server == null) {
148             mbeanServerContext.setUseMBeanServer(false);
149             mbeanServerContext.setCreateMBeanServer(false);
150         }
151         mbeanServerContext.setMBeanServer(server);
152         try {
153             mbeanServerContext.start();
154         } catch (IOException JavaDoc e) {
155             log.error("Failed to start mbeanServerContext", e);
156         }
157         this.executors = Executors.newCachedThreadPool();
158         super.init(container);
159     }
160     
161     protected Class JavaDoc getServiceMBean() {
162         return ManagementContextMBean.class;
163     }
164
165     /**
166      * Start the item.
167      *
168      * @exception JBIException if the item fails to start.
169      */

170     public void start() throws JBIException {
171         super.start();
172     }
173
174     /**
175      * Stop the item. This suspends current messaging activities.
176      *
177      * @exception JBIException if the item fails to stop.
178      */

179     public void stop() throws JBIException {
180         super.stop();
181     }
182
183     /**
184      * Shut down the item. The releases resources, preparatory to uninstallation.
185      *
186      * @exception JBIException if the item fails to shut down.
187      */

188     public void shutDown() throws JBIException {
189         super.shutDown();
190         // Unregister all mbeans
191
Object JavaDoc[] beans = beanMap.keySet().toArray();
192         for (int i = 0; i < beans.length; i++) {
193             try {
194                 unregisterMBean(beans[i]);
195             } catch (Exception JavaDoc e) {
196                 log.debug("Could not unregister mbean", e);
197             }
198         }
199         try{
200             mbeanServerContext.stop();
201         }catch(IOException JavaDoc e){
202             log.debug("Failed to shutdown mbeanServerContext cleanly",e);
203         }
204         executors.shutdown();
205     }
206
207     /**
208      * Get a list of all binding components currently installed.
209      *
210      * @return array of JMX object names of all installed BCs.
211      */

212     public ObjectName JavaDoc[] getBindingComponents() {
213         return container.getRegistry().getBindingComponents();
214     }
215
216     /**
217      * Lookup a JBI Installable Component by its unique name.
218      *
219      * @param componentName - is the name of the BC or SE.
220      * @return the JMX object name of the component's LifeCycle MBean or null.
221      */

222     public ObjectName JavaDoc getComponentByName(String JavaDoc componentName) {
223         ComponentMBeanImpl component = container.getRegistry().getComponent(componentName);
224         return component != null ? component.getMBeanName() : null;
225     }
226
227     /**
228      * Get a list of all engines currently installed.
229      *
230      * @return array of JMX object names of all installed SEs.
231      */

232     public ObjectName JavaDoc[] getEngineComponents() {
233         return container.getRegistry().getEngineComponents();
234     }
235     
236     /**
237      * @return an array of ObjectNames for all Pojo components
238      */

239     public ObjectName JavaDoc[] getPojoComponents(){
240         return container.getRegistry().getPojoComponents();
241     }
242
243     /**
244      * Return current version and other info about this JBI Framework.
245      *
246      * @return info String
247      */

248     public String JavaDoc getSystemInfo() {
249         return "ServiceMix JBI Container: version: " + EnvironmentContext.getVersion();
250     }
251
252     /**
253      * Lookup a system service by name.
254      *
255      * @param serviceName - is the name of the system service
256      * @return the JMX object name of the service or null
257      */

258     public ObjectName JavaDoc getSystemService(String JavaDoc serviceName) {
259         return (ObjectName JavaDoc) systemServices.get(serviceName);
260     }
261
262     /**
263      * Looks up all JBI Framework System Services currently installed.
264      *
265      * @return array of JMX object names of system services
266      */

267     public ObjectName JavaDoc[] getSystemServices() {
268         ObjectName JavaDoc[] result = null;
269         Collection JavaDoc col = systemServices.values();
270         result = new ObjectName JavaDoc[col.size()];
271         col.toArray(result);
272         return result;
273     }
274
275     /**
276      * Check if a given JBI Installable Component is a Binding Component.
277      *
278      * @param componentName - the unique name of the component
279      * @return true if the component is a binding
280      */

281     public boolean isBinding(String JavaDoc componentName) {
282         ComponentMBeanImpl component = container.getRegistry().getComponent(componentName);
283         return component != null ? component.isBinding() : false;
284     }
285
286     /**
287      * Check if a given JBI Component is a service engine.
288      *
289      * @param componentName - the unique name of the component
290      * @return true if the component is a service engine
291      */

292     public boolean isEngine(String JavaDoc componentName) {
293         ComponentMBeanImpl component = container.getRegistry().getComponent(componentName);
294         return component != null ? component.isEngine() : false;
295     }
296
297     /**
298      * Start a Component
299      *
300      * @param componentName
301      * @return the status
302      * @throws JBIException
303      */

304     public String JavaDoc startComponent(String JavaDoc componentName) throws JBIException {
305         String JavaDoc result = "NOT FOUND: " + componentName;
306         ObjectName JavaDoc objName = getComponentByName(componentName);
307         if (objName != null) {
308             ComponentMBeanImpl mbean = (ComponentMBeanImpl) beanMap.get(objName);
309             if (mbean != null) {
310                 mbean.start();
311                 result = mbean.getCurrentState();
312             }
313         }
314         return result;
315     }
316
317     /**
318      * Stop a Component
319      *
320      * @param componentName
321      * @return the status
322      * @throws JBIException
323      */

324     public String JavaDoc stopComponent(String JavaDoc componentName) throws JBIException {
325         String JavaDoc result = "NOT FOUND: " + componentName;
326         ObjectName JavaDoc objName = getComponentByName(componentName);
327         if (objName != null) {
328             ComponentMBeanImpl mbean = (ComponentMBeanImpl) beanMap.get(objName);
329             if (mbean != null) {
330                 mbean.stop();
331                 result = mbean.getCurrentState();
332             }
333         }
334         return result;
335     }
336
337     /**
338      * Shutdown a Component
339      *
340      * @param componentName
341      * @return the status
342      * @throws JBIException
343      */

344     public String JavaDoc shutDownComponent(String JavaDoc componentName) throws JBIException {
345         String JavaDoc result = "NOT FOUND: " + componentName;
346         ObjectName JavaDoc objName = getComponentByName(componentName);
347         if (objName != null) {
348             ComponentMBeanImpl mbean = (ComponentMBeanImpl) beanMap.get(objName);
349             if (mbean != null) {
350                 mbean.shutDown();
351                 result = mbean.getCurrentState();
352             }
353         }
354         return result;
355     }
356
357     /**
358      * Formulate and return the MBean ObjectName of a custom control MBean for a JBI component.
359      *
360      * @param type
361      * @param name
362      * @return the JMX ObjectName of the MBean, or <code>null</code> if <code>customName</code> is invalid.
363      */

364     public ObjectName JavaDoc createCustomComponentMBeanName(String JavaDoc type, String JavaDoc name) {
365         Map JavaDoc result = new LinkedHashMap JavaDoc();
366         result.put("ContainerName", container.getName());
367         result.put("Type", "Component");
368         result.put("Name", sanitizeString(name));
369         result.put("SubType", sanitizeString(type));
370         return createObjectName(result);
371     }
372
373     
374     /**
375      * Create an ObjectName
376      *
377      * @param provider
378      * @return the ObjectName
379      */

380     public ObjectName JavaDoc createObjectName(MBeanInfoProvider provider) {
381         Map JavaDoc props = createObjectNameProps(provider);
382         return createObjectName(props);
383     }
384     
385     /**
386      * Create an ObjectName
387      * @param name
388      *
389      * @return the ObjectName
390      */

391     public ObjectName JavaDoc createObjectName(String JavaDoc name) {
392         ObjectName JavaDoc result = null;
393         try {
394             result = new ObjectName JavaDoc(name);
395         }
396         catch (MalformedObjectNameException JavaDoc e) {
397             // shouldn't happen
398
String JavaDoc error = "Could not create ObjectName for " + name;
399             log.error(error, e);
400             throw new RuntimeException JavaDoc(error);
401         }
402         return result;
403     }
404     
405     /**
406      * Create an ObjectName
407      * @param domain
408      *
409      * @return the ObjectName
410      */

411     public ObjectName JavaDoc createObjectName(String JavaDoc domain, Map JavaDoc props) {
412         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
413         sb.append(domain).append(':');
414         int i = 0;
415         for (Iterator JavaDoc it = props.entrySet().iterator(); it.hasNext();) {
416             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
417             if (i++ > 0) {
418                 sb.append(",");
419             }
420             sb.append(entry.getKey()).append("=").append(entry.getValue());
421         }
422         ObjectName JavaDoc result = null;
423         try {
424             result = new ObjectName JavaDoc(sb.toString());
425         }
426         catch (MalformedObjectNameException JavaDoc e) {
427             // shouldn't happen
428
String JavaDoc error = "Could not create ObjectName for " + props;
429             log.error(error, e);
430             throw new RuntimeException JavaDoc(error);
431         }
432         return result;
433     }
434     
435     /**
436      * Create an ObjectName
437      * @param props
438      * @return the ObjectName
439      */

440     public ObjectName JavaDoc createObjectName(Map JavaDoc props) {
441         return createObjectName(getJmxDomainName(), props);
442     }
443     
444     /**
445      * Create a String used to create an ObjectName
446      *
447      * @param provider
448      * @return the ObjectName
449      */

450     public Map JavaDoc createObjectNameProps(MBeanInfoProvider provider){
451         Map JavaDoc result = new LinkedHashMap JavaDoc();
452         result.put("ContainerName", container.getName());
453         result.put("Type", sanitizeString(provider.getType()));
454         result.put("Name", sanitizeString(provider.getName()));
455         if (provider.getSubType() != null) {
456             result.put("SubType", sanitizeString(provider.getSubType()));
457         }
458         return result;
459     }
460
461     /**
462      * The ':' and '/' characters are reserved in ObjectNames
463      *
464      * @param in
465      * @return sanitized String
466      */

467     private static String JavaDoc sanitizeString(String JavaDoc in) {
468         String JavaDoc result = null;
469         if (in != null) {
470             result = in.replace(':', '_');
471             result = result.replace('/', '_');
472             result = result.replace('\\', '_');
473             result = result.replace('?', '_');
474             result = result.replace('=', '_');
475             result = result.replace(',', '_');
476         }
477         return result;
478     }
479
480     /**
481      * Register an MBean
482      *
483      * @param resource
484      * @param name
485      * @param interfaceMBean
486      * @throws JMException
487      */

488     public void registerMBean(ObjectName JavaDoc name, MBeanInfoProvider resource, Class JavaDoc interfaceMBean) throws JMException JavaDoc {
489         registerMBean(name, resource, interfaceMBean, resource.getDescription());
490     }
491
492     /**
493      * Register an MBean
494      *
495      * @param resource
496      * @param name
497      * @param interfaceMBean
498      * @param description
499      * @throws JMException
500      */

501     public void registerMBean(ObjectName JavaDoc name, Object JavaDoc resource, Class JavaDoc interfaceMBean, String JavaDoc description)
502             throws JMException JavaDoc {
503         if (mbeanServerContext.getMBeanServer() != null) {
504             Object JavaDoc mbean = MBeanBuilder.buildStandardMBean(resource, interfaceMBean, description, executors);
505             if (mbeanServerContext.getMBeanServer().isRegistered(name)) {
506                 mbeanServerContext.getMBeanServer().unregisterMBean(name);
507             }
508             mbeanServerContext.getMBeanServer().registerMBean(mbean, name);
509             beanMap.put(name, resource);
510         }
511     }
512
513
514     /**
515      * Retrive an System ObjectName
516      *
517      * @param domainName
518      * @param containerName
519      * @param interfaceType
520      * @return the ObjectName
521      */

522     public static ObjectName JavaDoc getSystemObjectName(String JavaDoc domainName, String JavaDoc containerName, Class JavaDoc interfaceType) {
523         String JavaDoc tmp = domainName + ":ContainerName=" + containerName + ",Type=SystemService,Name=" + getSystemServiceName(interfaceType);
524         ObjectName JavaDoc result = null;
525         try {
526             result = new ObjectName JavaDoc(tmp);
527         }
528         catch (MalformedObjectNameException JavaDoc e) {
529             log.error("Failed to build ObjectName:",e);
530         }
531         catch (NullPointerException JavaDoc e) {
532             log.error("Failed to build ObjectName:",e);
533         }
534         return result;
535     }
536     
537     public static String JavaDoc getSystemServiceName(Class JavaDoc interfaceType) {
538         String JavaDoc name = interfaceType.getName();
539         name = name.substring(name.lastIndexOf('.') + 1);
540         if (name.endsWith("MBean")) {
541             name = name.substring(0, name.length() - 5);
542         }
543         return name;
544     }
545     
546     public static ObjectName JavaDoc getContainerObjectName(String JavaDoc domainName, String JavaDoc containerName) {
547         String JavaDoc tmp = domainName + ":ContainerName=" + containerName + ",Type=JBIContainer";
548         ObjectName JavaDoc result = null;
549         try {
550             result = new ObjectName JavaDoc(tmp);
551         }
552         catch (MalformedObjectNameException JavaDoc e) {
553             // TODO Auto-generated catch block
554
e.printStackTrace();
555         }
556         catch (NullPointerException JavaDoc e) {
557             // TODO Auto-generated catch block
558
e.printStackTrace();
559         }
560         return result;
561     }
562
563     /**
564      * Register a System service
565      *
566      * @param service
567      * @param interfaceType
568      * @throws JBIException
569      */

570     public void registerSystemService(BaseSystemService service, Class JavaDoc interfaceType) throws JBIException {
571         try {
572
573             String JavaDoc name = service.getName();
574             if (systemServices.containsKey(name)) {
575                 throw new JBIException("A system service for the name " + name + " is already registered");
576             }
577             ObjectName JavaDoc objName = createObjectName(service);
578             if (log.isDebugEnabled()) {
579                 log.debug("Registering system service: " + objName);
580             }
581             registerMBean(objName, service, interfaceType, service.getDescription());
582             systemServices.put(name, objName);
583         }
584         catch (MalformedObjectNameException JavaDoc e) {
585             throw new JBIException(e);
586         }
587         catch (JMException JavaDoc e) {
588             throw new JBIException(e);
589         }
590     }
591
592     /**
593      * Unregister a System service
594      *
595      * @param service
596      * @throws JBIException
597      */

598     public void unregisterSystemService(BaseSystemService service) throws JBIException {
599         String JavaDoc name = service.getName();
600         if (!systemServices.containsKey(name)) {
601             throw new JBIException("A system service for the name " + name + " is not registered");
602         }
603         ObjectName JavaDoc objName = (ObjectName JavaDoc)systemServices.remove(name);
604         if (log.isDebugEnabled()) {
605             log.debug("Unregistering system service: " + objName);
606         }
607         unregisterMBean(objName);
608     }
609
610     /**
611      * Unregister an MBean
612      *
613      * @param name
614      * @throws JBIException
615      */

616     public void unregisterMBean(ObjectName JavaDoc name) throws JBIException {
617         try{
618             mbeanServerContext.unregisterMBean(name);
619             beanMap.remove(name);
620         }catch(JMException JavaDoc e){
621             log.error("Failed to unregister mbean: " + name,e);
622             throw new JBIException(e);
623         }
624     }
625
626     /**
627      * Unregister an MBean
628      *
629      * @param bean
630      * @throws JBIException
631      */

632     public void unregisterMBean(Object JavaDoc bean) throws JBIException {
633         for (Iterator JavaDoc i = beanMap.entrySet().iterator();i.hasNext();) {
634             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
635             if (entry.getValue() == bean) {
636                 ObjectName JavaDoc name = (ObjectName JavaDoc) entry.getKey();
637                 unregisterMBean(name);
638                 break;
639             }
640         }
641     }
642
643    
644
645     /**
646      * Get an array of MBeanOperationInfo
647      *
648      * @return array of OperationInfos
649      * @throws JMException
650      */

651     public MBeanAttributeInfo JavaDoc[] getAttributeInfos() throws JMException JavaDoc {
652         AttributeInfoHelper helper = new AttributeInfoHelper();
653         helper.addAttribute(getObjectToManage(), "bindingComponents", "Get list of all binding components");
654         helper.addAttribute(getObjectToManage(), "engineComponents", "Get list of all engine components");
655         helper.addAttribute(getObjectToManage(), "pojoComponents", "Get list of all pojo components");
656         helper.addAttribute(getObjectToManage(), "systemInfo", "Return current version");
657         helper.addAttribute(getObjectToManage(), "systemServices", "Get list of system services");
658         return AttributeInfoHelper.join(super.getAttributeInfos(), helper.getAttributeInfos());
659     }
660
661     public MBeanOperationInfo JavaDoc[] getOperationInfos() throws JMException JavaDoc {
662         OperationInfoHelper helper = new OperationInfoHelper();
663         ParameterHelper ph = helper.addOperation(getObjectToManage(), "getComponentByName", 1, "look up Component by name");
664         ph.setDescription(0, "name", "Component name");
665         ph = helper.addOperation(getObjectToManage(), "getSystemService", 1, "look up System service by name");
666         ph.setDescription(0, "name", "System name");
667         ph = helper.addOperation(getObjectToManage(), "isBinding", 1, "Is Component a binding Component?");
668         ph.setDescription(0, "name", "Component name");
669         ph = helper.addOperation(getObjectToManage(), "isEngine", 1, "Is Component a service engine?");
670         ph.setDescription(0, "name", "Component name");
671         return OperationInfoHelper.join(super.getOperationInfos(), helper.getOperationInfos());
672     }
673     
674 }
Popular Tags