KickJava   Java API By Example, From Geeks To Geeks.

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


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.lang.reflect.Method JavaDoc;
21 import java.rmi.RemoteException JavaDoc;
22 import java.util.List JavaDoc;
23
24 import javax.management.JMException JavaDoc;
25 import javax.management.MBeanServer JavaDoc;
26 import javax.management.MBeanServerFactory JavaDoc;
27 import javax.management.MalformedObjectNameException JavaDoc;
28 import javax.management.ObjectName JavaDoc;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.servicemix.jbi.jmx.ConnectorServerFactoryBean;
33 import org.apache.servicemix.jbi.jmx.RmiRegistryFactoryBean;
34
35 import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;
36
37
38 /**
39  *Wrapper around ActiveMQ ManagementContext. Re-use to build/find mbean server
40  *
41  * @version $Revision: 372580 $
42  */

43 class MBeanServerContext {
44
45     /**
46      * Default activemq domain
47      */

48     public static final String JavaDoc DEFAULT_DOMAIN="org.apache.activemq";
49     private final static Log log=LogFactory.getLog(ManagementContext.class);
50     private MBeanServer JavaDoc beanServer;
51     private String JavaDoc jmxDomainName=DEFAULT_DOMAIN;
52     private boolean useMBeanServer=true;
53     private boolean createMBeanServer=true;
54     private boolean locallyCreateMBeanServer=false;
55     private boolean createConnector=true;
56     private boolean findTigerMbeanServer=false;
57     private int connectorPort=1099;
58     private String JavaDoc connectorPath="/jmxrmi";
59     private AtomicBoolean started=new AtomicBoolean(false);
60     private ConnectorServerFactoryBean connectorServerFactoryBean;
61     private RmiRegistryFactoryBean rmiRegistryFactoryBean;
62
63     public MBeanServerContext(){
64         this(null);
65     }
66
67     public MBeanServerContext(MBeanServer JavaDoc server){
68         this.beanServer=server;
69     }
70
71     public void start() throws IOException JavaDoc {
72         // lets force the MBeanServer to be created if needed
73
if (started.compareAndSet(false, true)) {
74             getMBeanServer();
75             if (createConnector) {
76                 try {
77                     rmiRegistryFactoryBean = new RmiRegistryFactoryBean();
78                     rmiRegistryFactoryBean.setPort(connectorPort);
79                     rmiRegistryFactoryBean.afterPropertiesSet();
80                 } catch (Exception JavaDoc e) {
81                     log.warn("Failed to start rmi registry: " + e.getMessage());
82                     if (log.isDebugEnabled()) {
83                         log.debug("Failed to start rmi registry", e);
84                     }
85                 }
86                 try {
87                     connectorServerFactoryBean = new ConnectorServerFactoryBean();
88                     //connectorServerFactoryBean.setDaemon(true);
89
connectorServerFactoryBean.setObjectName("connector:name=rmi");
90                     //connectorServerFactoryBean.setThreaded(true);
91
connectorServerFactoryBean.setServer(getMBeanServer());
92                     String JavaDoc serviceUrl = "service:jmx:rmi:///jndi/rmi://localhost:" + connectorPort + connectorPath;
93                     connectorServerFactoryBean.setServiceUrl(serviceUrl);
94                     connectorServerFactoryBean.afterPropertiesSet();
95                 } catch (Exception JavaDoc e) {
96                     log.warn("Failed to start jmx connector: " + e.getMessage());
97                     if (log.isDebugEnabled()) {
98                         log.debug("Failed to create jmx connector", e);
99                     }
100                 }
101             }
102         }
103     }
104
105     public void stop() throws IOException JavaDoc {
106         if (started.compareAndSet(true, false)) {
107             if (connectorServerFactoryBean != null) {
108                 try {
109                     connectorServerFactoryBean.destroy();
110                 } catch (Exception JavaDoc e) {
111                     log.warn("Failed to stop jmx connector: " + e.getMessage());
112                     if (log.isDebugEnabled()) {
113                         log.debug("Failed to stop jmx connector", e);
114                     }
115                 } finally {
116                     connectorServerFactoryBean = null;
117                 }
118             }
119             if (rmiRegistryFactoryBean != null) {
120                 try {
121                     rmiRegistryFactoryBean.destroy();
122                 } catch (RemoteException JavaDoc e) {
123                     log.warn("Failed to stop rmi registry: " + e.getMessage());
124                     if (log.isDebugEnabled()) {
125                         log.debug("Failed to stop rmi registry", e);
126                     }
127                 } finally {
128                     rmiRegistryFactoryBean = null;
129                 }
130             }
131             if (locallyCreateMBeanServer && beanServer != null) {
132                 // check to see if the factory knows about this server
133
List JavaDoc list = MBeanServerFactory.findMBeanServer(null);
134                 if (list != null && !list.isEmpty() && list.contains(beanServer)) {
135                     MBeanServerFactory.releaseMBeanServer(beanServer);
136                 }
137             }
138         }
139     }
140
141     /**
142      * @return Returns the jmxDomainName.
143      */

144     public String JavaDoc getJmxDomainName(){
145         return jmxDomainName;
146     }
147
148     /**
149      * @param jmxDomainName
150      * The jmxDomainName to set.
151      */

152     public void setJmxDomainName(String JavaDoc jmxDomainName){
153         this.jmxDomainName=jmxDomainName;
154     }
155
156     /**
157      * Get the MBeanServer
158      *
159      * @return the MBeanServer
160      */

161     public MBeanServer JavaDoc getMBeanServer(){
162         if(this.beanServer==null){
163             this.beanServer=findMBeanServer();
164         }
165         return beanServer;
166     }
167
168     /**
169      * Set the MBeanServer
170      *
171      * @param beanServer
172      */

173     public void setMBeanServer(MBeanServer JavaDoc beanServer){
174         this.beanServer=beanServer;
175     }
176
177     /**
178      * @return Returns the useMBeanServer.
179      */

180     public boolean isUseMBeanServer(){
181         return useMBeanServer;
182     }
183
184     /**
185      * @param useMBeanServer
186      * The useMBeanServer to set.
187      */

188     public void setUseMBeanServer(boolean useMBeanServer){
189         this.useMBeanServer=useMBeanServer;
190     }
191
192     /**
193      * @return Returns the createMBeanServer flag.
194      */

195     public boolean isCreateMBeanServer(){
196         return createMBeanServer;
197     }
198
199     /**
200      * @param enableJMX
201      * Set createMBeanServer.
202      */

203     public void setCreateMBeanServer(boolean enableJMX){
204         this.createMBeanServer=enableJMX;
205     }
206
207     public boolean isFindTigerMbeanServer() {
208         return findTigerMbeanServer;
209     }
210
211     /**
212      * Enables/disables the searching for the Java 5 platform MBeanServer
213      */

214     public void setFindTigerMbeanServer(boolean findTigerMbeanServer) {
215         this.findTigerMbeanServer = findTigerMbeanServer;
216     }
217
218     /**
219      * Formulate and return the MBean ObjectName of a custom control MBean
220      *
221      * @param type
222      * @param name
223      * @return the JMX ObjectName of the MBean, or <code>null</code> if <code>customName</code> is invalid.
224      */

225     public ObjectName JavaDoc createCustomComponentMBeanName(String JavaDoc type,String JavaDoc name){
226         ObjectName JavaDoc result=null;
227         String JavaDoc tmp=jmxDomainName+":"+"type="+sanitizeString(type)+",name="+sanitizeString(name);
228         try{
229             result=new ObjectName JavaDoc(tmp);
230         }catch(MalformedObjectNameException JavaDoc e){
231             log.error("Couldn't create ObjectName from: "+type+" , "+name);
232         }
233         return result;
234     }
235
236     /**
237      * The ':' and '/' characters are reserved in ObjectNames
238      *
239      * @param in
240      * @return sanitized String
241      */

242     private static String JavaDoc sanitizeString(String JavaDoc in){
243         String JavaDoc result=null;
244         if(in!=null){
245             result=in.replace(':','_');
246             result=result.replace('/','_');
247             result=result.replace('\\','_');
248         }
249         return result;
250     }
251
252     /**
253      * Retrive an System ObjectName
254      *
255      * @param domainName
256      * @param containerName
257      * @param theClass
258      * @return the ObjectName
259      * @throws MalformedObjectNameException
260      */

261     public static ObjectName JavaDoc getSystemObjectName(String JavaDoc domainName,String JavaDoc containerName,Class JavaDoc theClass)
262                     throws MalformedObjectNameException JavaDoc,NullPointerException JavaDoc{
263         String JavaDoc tmp=domainName+":"+"type="+theClass.getName()+",name="+getRelativeName(containerName,theClass);
264         return new ObjectName JavaDoc(tmp);
265     }
266
267     private static String JavaDoc getRelativeName(String JavaDoc containerName,Class JavaDoc theClass){
268         String JavaDoc name=theClass.getName();
269         int index=name.lastIndexOf(".");
270         if(index>=0&&(index+1)<name.length()){
271             name=name.substring(index+1);
272         }
273         return containerName+"."+name;
274     }
275
276     /**
277      * Unregister an MBean
278      *
279      * @param name
280      * @throws JMException
281      */

282     public void unregisterMBean(ObjectName JavaDoc name) throws JMException JavaDoc{
283         if(beanServer!=null&&beanServer.isRegistered(name)){
284             beanServer.unregisterMBean(name);
285         }
286     }
287
288     protected synchronized MBeanServer JavaDoc findMBeanServer(){
289         MBeanServer JavaDoc result=null;
290         // create the mbean server
291
try{
292             if(useMBeanServer){
293                 if (findTigerMbeanServer) {
294                     result = findTigerMBeanServer();
295                 }
296                 if (result == null) {
297                     // lets piggy back on another MBeanServer -
298
// we could be in an appserver!
299
List JavaDoc list=MBeanServerFactory.findMBeanServer(null);
300                     if(list!=null&&list.size()>0){
301                         result=(MBeanServer JavaDoc) list.get(0);
302                     }
303                 }
304             }
305             if(result==null&&createMBeanServer){
306                 result=createMBeanServer();
307             }
308         }catch(NoClassDefFoundError JavaDoc e){
309             log.error("Could not load MBeanServer",e);
310         }catch(Throwable JavaDoc e){
311             // probably don't have access to system properties
312
log.error("Failed to initialize MBeanServer",e);
313         }
314         return result;
315     }
316
317     public static MBeanServer JavaDoc findTigerMBeanServer() {
318         String JavaDoc name = "java.lang.management.ManagementFactory";
319         Class JavaDoc type = loadClass(name, ManagementContext.class.getClassLoader());
320         if (type != null) {
321             try {
322                 Method JavaDoc method = type.getMethod("getPlatformMBeanServer", new Class JavaDoc[0]);
323                 if (method != null) {
324                     Object JavaDoc answer = method.invoke(null, new Object JavaDoc[0]);
325                     if (answer instanceof MBeanServer JavaDoc) {
326                         return (MBeanServer JavaDoc) answer;
327                     }
328                     else {
329                         log.warn("Could not cast: " + answer + " into an MBeanServer. There must be some classloader strangeness in town");
330                     }
331                 }
332                 else {
333                     log.warn("Method getPlatformMBeanServer() does not appear visible on type: " + type.getName());
334                 }
335             }
336             catch (Exception JavaDoc e) {
337                 log.warn("Failed to call getPlatformMBeanServer() due to: " + e, e);
338             }
339         }
340         else {
341             log.trace("Class not found: " + name + " so probably running on Java 1.4");
342         }
343         return null;
344     }
345
346     private static Class JavaDoc loadClass(String JavaDoc name, ClassLoader JavaDoc loader) {
347         try {
348             return loader.loadClass(name);
349         }
350         catch (ClassNotFoundException JavaDoc e) {
351             try {
352                 return Thread.currentThread().getContextClassLoader().loadClass(name);
353             }
354             catch (ClassNotFoundException JavaDoc e1) {
355                 return null;
356             }
357         }
358     }
359
360     /**
361      * @return
362      * @throws NullPointerException
363      * @throws MalformedObjectNameException
364      * @throws IOException
365      */

366     protected MBeanServer JavaDoc createMBeanServer() throws MalformedObjectNameException JavaDoc,IOException JavaDoc{
367         MBeanServer JavaDoc mbeanServer=MBeanServerFactory.createMBeanServer(jmxDomainName);
368         locallyCreateMBeanServer=true;
369         return mbeanServer;
370     }
371
372     public String JavaDoc getConnectorPath(){
373         return connectorPath;
374     }
375
376     public void setConnectorPath(String JavaDoc connectorPath){
377         this.connectorPath=connectorPath;
378     }
379
380     public int getConnectorPort(){
381         return connectorPort;
382     }
383
384     public void setConnectorPort(int connectorPort){
385         this.connectorPort=connectorPort;
386     }
387
388     public boolean isCreateConnector(){
389         return createConnector;
390     }
391
392     public void setCreateConnector(boolean createConnector){
393         this.createConnector=createConnector;
394     }
395 }
396
Popular Tags