KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > jmx > JmxServiceImpl


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2005 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: JmxServiceImpl.java,v 1.42 2005/05/23 11:09:31 danesa Exp $
23  * --------------------------------------------------------------------------
24  */

25 package org.objectweb.jonas.jmx;
26
27 import java.io.IOException JavaDoc;
28 import java.lang.reflect.Method JavaDoc;
29 import java.net.URI JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Properties JavaDoc;
35
36 import javax.management.InstanceNotFoundException JavaDoc;
37 import javax.management.JMException JavaDoc;
38 import javax.management.ListenerNotFoundException JavaDoc;
39 import javax.management.MBeanServerConnection JavaDoc;
40 import javax.management.MBeanServerNotification JavaDoc;
41 import javax.management.Notification JavaDoc;
42 import javax.management.NotificationListener JavaDoc;
43 import javax.management.ObjectName JavaDoc;
44 import javax.management.remote.JMXConnector JavaDoc;
45 import javax.management.remote.JMXConnectorFactory JavaDoc;
46 import javax.management.remote.JMXConnectorServer JavaDoc;
47 import javax.management.remote.JMXConnectorServerFactory JavaDoc;
48 import javax.management.remote.JMXServiceURL JavaDoc;
49 import javax.naming.Context JavaDoc;
50 import javax.naming.InitialContext JavaDoc;
51 import javax.naming.NamingException JavaDoc;
52
53 import org.objectweb.carol.rmi.util.PortNumber;
54 import org.objectweb.carol.util.configuration.CarolDefaultValues;
55 import org.objectweb.carol.util.configuration.ConfigurationRepository;
56 import org.objectweb.carol.util.configuration.ProtocolConfiguration;
57
58 import org.objectweb.jonas.common.Log;
59 import org.objectweb.jonas.discovery.DiscEvent;
60 import org.objectweb.jonas.service.JonasAlreadyStartedException;
61 import org.objectweb.jonas.service.ServiceException;
62
63 import org.objectweb.util.monolog.api.BasicLevel;
64 import org.objectweb.util.monolog.api.Logger;
65
66 /**
67  * JMX Service implementation.
68  * Provides specific doStart() and doStop () methods to start /stop
69  * JOnAS JMX Service.
70
71  * @author Adriana Danes.
72  *
73  */

74
75 public class JmxServiceImpl extends AbsJmxServiceImpl implements NotificationListener JavaDoc {
76
77     /**
78      * MX4J CommonsLogger fully qualified Classname
79      */

80     private static final String JavaDoc MX4J_COMMONS_LOGGER_CLASSNAME = "mx4j.log.CommonsLogger";
81
82     /**
83      * MX4J Log class
84      */

85     private static final String JavaDoc MX4J_LOG_CLASSNAME = "mx4j.log.Log";
86
87     /**
88      * MX4J Logger class
89      */

90     private static final String JavaDoc MX4J_LOGGER_CLASS = "mx4j.log.Logger";
91
92     /**
93      * The JNDI name of the JOnAS RMI connector allowing to access the
94      * MBeanServer remotelly. Use of this connector was needed before
95      * the definition of the Connectors in JMX (before JMX 1.2)
96      */

97     private String JavaDoc rmiConnectorName = null;
98
99     /**
100      * @return The JNDI name of the JOnAS RMI connector
101      */

102     public String JavaDoc getRmiConnectorName() {
103         return this.rmiConnectorName;
104     }
105
106     /**
107      * Protocol that can be defined by carol configuration
108      */

109     private static final String JavaDoc JRMP = "jrmp";
110     /**
111      * Protocol that can be defined by carol configuration
112      */

113     private static final String JavaDoc IIOP = "iiop";
114     /**
115      * Protocol that can be defined by carol configuration
116      */

117     private static final String JavaDoc JEREMIE = "jeremie";
118     /**
119      * Protocol that can be defined by carol configuration
120      */

121     private static final String JavaDoc CMI = "cmi";
122     /**
123      * Connector servers attached to the MBean server.
124      * We may have several connector servers only
125      * if several communication protocols are used, as defined by the
126      * carol configuration.
127      */

128     private JMXConnectorServer JavaDoc[] connectorServers = null;
129
130     /**
131      * The JMXServiceURLs the connector servers are actually listening on.
132      */

133     private JMXServiceURL JavaDoc[] connectorServerURLs = null;
134
135     // Domain management support
136
/**
137      * Mapping serverName -> JMX Service URLs published by the server
138      */

139     private Map JavaDoc managedServersToUrls = null;
140     /**
141      * Mapping serverName -> JMX Service connector
142      */

143     private Map JavaDoc managedServersToConnectors = null;
144     /**
145      * Mapping serverName -> JMX Service connection
146      */

147     private Map JavaDoc managedServersToConnections = null;
148
149     /**
150      * Management loggers
151      */

152     private static Logger logger = Log.getLogger(Log.JONAS_JMX_PREFIX);
153     private static Logger loggerDomain = Log.getLogger(Log.JONAS_DOMAIN_MANAGEMENT_PREFIX);
154     /**
155      * Init the logger and then use super method.
156      * @param ctx configuration for the init method
157      * @throws ServiceException if initialization failed
158      */

159     public void doInit(Context JavaDoc ctx) throws ServiceException {
160         // Test if MX4J CommonsLoggger class is present.
161
// In this case, redirect MX4J logging to Jakarta Commons Logging.
162
Class JavaDoc mx4jCommonsLoggerClass = null;
163         try {
164             mx4jCommonsLoggerClass = Thread.currentThread().getContextClassLoader().loadClass(MX4J_COMMONS_LOGGER_CLASSNAME);
165             if (logger.isLoggable(BasicLevel.DEBUG)) {
166                 logger.log(BasicLevel.DEBUG, "Class " + MX4J_COMMONS_LOGGER_CLASSNAME + " founded");
167             }
168             Object JavaDoc o = mx4jCommonsLoggerClass.newInstance();
169
170
171
172             // Load Log a Logger class
173
Class JavaDoc clazz = Thread.currentThread().getContextClassLoader().loadClass(MX4J_LOG_CLASSNAME);
174             Class JavaDoc mx4jLoggerClass = Thread.currentThread().getContextClassLoader().loadClass(MX4J_LOGGER_CLASS);
175
176
177             // Then get method redirectTo
178
Method JavaDoc m = clazz.getMethod("redirectTo", new Class JavaDoc[] {mx4jLoggerClass});
179             m.invoke(clazz, new Object JavaDoc[] {o});
180             if (logger.isLoggable(BasicLevel.DEBUG)) {
181                 logger.log(BasicLevel.DEBUG, "MX4J logging redirected to the Jakarta commons logger");
182             }
183         } catch (ClassNotFoundException JavaDoc cnfe) {
184             if (logger.isLoggable(BasicLevel.DEBUG)) {
185                 logger.log(BasicLevel.DEBUG, "Class " + MX4J_COMMONS_LOGGER_CLASSNAME + " not found: " + cnfe);
186             }
187         } catch (Exception JavaDoc e) {
188             if (logger.isLoggable(BasicLevel.WARN)) {
189                 logger.log(BasicLevel.WARN, "Problem with " + MX4J_COMMONS_LOGGER_CLASSNAME + " instance creation " + e);
190             }
191         }
192         super.doInit(ctx);
193     }
194     /**
195      * Start the Service.
196      * Only need to create a RMI connector
197      * @exception ServiceException the service could not be started
198      */

199     public void doStart() throws ServiceException {
200         String JavaDoc serverName = getJonasServerName();
201         try {
202             // Create a RMI Connector for the JMX agent using the JOnAS RMIConnector class
203
// --------------------------------------------------------------------------
204
RMIConnector rmiConnector = new RMIConnectorImpl(getJmxServer());
205             // Register the connector in JNDI
206
InitialContext JavaDoc ictx = new InitialContext JavaDoc();
207             rmiConnectorName = "RMIConnector_" + serverName;
208             ictx.rebind(rmiConnectorName, rmiConnector);
209             ictx.close();
210
211             // Create one or more connector servers
212
// (cf. JSR 160, JMX Remote 1.0)
213
// Create a JMXServiceURL and a JMXConnectorServer per protocol
214
// As some protocols does not have associated connectors, the
215
// 2 arrays below may have null values
216
// ------------------------------------
217
int nbProtocols = ConfigurationRepository.getActiveConfigurationsNumber();
218             connectorServerURLs = new JMXServiceURL JavaDoc[nbProtocols];
219             connectorServers = new JMXConnectorServer JavaDoc[nbProtocols];
220             // Determine protocols used by Carol and their configuration
221
ProtocolConfiguration[] protocolConfigurations = ConfigurationRepository.getConfigurations();
222             String JavaDoc serviceURL = null;
223             for (int i = 0; i < protocolConfigurations.length; i++) {
224                 String JavaDoc carolProtocol = protocolConfigurations[i].getName();
225                 String JavaDoc providerUrl = protocolConfigurations[i].getProviderURL();
226                 URI JavaDoc carolURL = new URI JavaDoc(providerUrl);
227                 String JavaDoc host = carolURL.getHost();
228                 String JavaDoc port = String.valueOf(carolURL.getPort());
229                 String JavaDoc scheme = carolURL.getScheme();
230                 String JavaDoc ictxFactory = protocolConfigurations[i].getProtocol().getInitialContextFactoryClassName();
231                 Properties JavaDoc props = new Properties JavaDoc();
232                 if (scheme.equals("rmi")) {
233                     // Treat RMI/JRMP cas
234
String JavaDoc myName = "jrmpconnector_" + serverName;
235                     serviceURL = "service:jmx:rmi://" + host;
236                     int jrmpExportedPort = 0;
237                     // Add port number of exported objects if one is set by carol.
238
String JavaDoc propertyName = CarolDefaultValues.SERVER_JRMP_PORT;
239                     Properties JavaDoc p = ConfigurationRepository.getProperties();
240                     if (p != null) {
241                         jrmpExportedPort = PortNumber.strToint(p.getProperty(propertyName, "0"), propertyName);
242                     }
243                     if (jrmpExportedPort > 0) {
244                         serviceURL += ":" + jrmpExportedPort;
245                     }
246                     serviceURL += "/jndi/rmi://"
247                         + host + ":" + port + "/"
248                         + myName;
249
250                     props.put(Context.INITIAL_CONTEXT_FACTORY, ictxFactory);
251                     props.put(Context.PROVIDER_URL, providerUrl);
252                 } else if (scheme.equals("jrmi")) {// Treat JEREMIE case
253
String JavaDoc myName = "jeremieconnector_" + serverName;
254                     serviceURL = "service:jmx:rmi://" + host;
255                     int jeremieExportedPort = 0;
256                     // Add port number of exported objects if one is set by carol.
257
String JavaDoc propertyName = CarolDefaultValues.SERVER_JEREMIE_PORT;
258                     Properties JavaDoc p = ConfigurationRepository.getProperties();
259                     if (p != null) {
260                         jeremieExportedPort = PortNumber.strToint(p.getProperty(propertyName, "0"), propertyName);
261                         // Add 1 to this port for jeremie as the JMX object will not use jeremie to bind but JRMP methods.
262
jeremieExportedPort++;
263                     }
264                     if (jeremieExportedPort > 1024) {
265                         serviceURL += ":" + jeremieExportedPort;
266                     }
267                     serviceURL += "/jndi/jrmi://"
268                         + host + ":" + port + "/"
269                         + myName;
270
271                     props.put(Context.INITIAL_CONTEXT_FACTORY, ictxFactory);
272                     props.put(Context.PROVIDER_URL, providerUrl);
273                 } else if (scheme.equals("cmi")) {
274                     // Treat CMI case
275
String JavaDoc myName = "cmiconnector_" + serverName;
276                     serviceURL = "service:jmx:rmi://" + host
277                         + "/jndi/cmi://"
278                         + host + ":" + port + "/"
279                         + myName;
280                     props.put(Context.INITIAL_CONTEXT_FACTORY, ictxFactory);
281                     props.put(Context.PROVIDER_URL, providerUrl);
282                 } else if (scheme.equals("iiop")) {
283                     // Treat RMI/IIOP case
284
String JavaDoc myName = "iiopconnector_" + serverName;
285                     //serviceURL = "service:jmx:iiop://" + host + "/jndi/" + myName;
286

287                     serviceURL = "service:jmx:iiop://" + host
288                         + "/jndi/iiop://"
289                         + host + ":" + port + "/"
290                         + myName;
291
292                     props.put("java.naming.corba.orb", new InitialContext JavaDoc().lookup("java:comp/ORB"));
293                 } else {
294                     // Currently do not create connectors for other protocols.
295
connectorServerURLs[i] = null;
296                     continue;
297                 }
298
299                 JMXServiceURL JavaDoc url = new JMXServiceURL JavaDoc(serviceURL);
300                 // Cast to Map is required for JDK 1.5
301
JMXConnectorServer JavaDoc connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, (Map JavaDoc) props, null);
302                 connectorServers[i] = connectorServer;
303                 // Create the MBean associated to the connector
304
String JavaDoc connectorObjectName = "connector_" + carolProtocol;
305                 ObjectName JavaDoc connectorServerName = JonasObjectName.jmxConnectorServer(scheme, connectorObjectName);
306                 getJmxServer().registerMBean(connectorServer, connectorServerName);
307                 // Start the JMXConnectorServer
308
try {
309                     connectorServer.start();
310                     connectorServerURLs[i] = connectorServer.getAddress();
311                 } catch (IllegalArgumentException JavaDoc e) {
312                     throw e;
313                 }
314             }
315         } catch (javax.naming.NameAlreadyBoundException JavaDoc ne) {
316             if (logger.isLoggable(BasicLevel.DEBUG)) {
317                 logger.log(BasicLevel.DEBUG, "Cannot start JMX service " + ne);
318             }
319             throw new JonasAlreadyStartedException();
320         } catch (Exception JavaDoc e) {
321             if (logger.isLoggable(BasicLevel.DEBUG)) {
322                 logger.log(BasicLevel.DEBUG, "Cannot start JMX service " + e);
323             }
324             throw new ServiceException("Cannot start JMX service", e);
325         }
326
327         // Registers as listener to notifications emitted by MBeanServerDelegate
328
// MBeanServerDelegate is the MBean which sends registration/unregistration notifications
329
try {
330             ObjectName JavaDoc delegate = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
331             getJmxServer().addNotificationListener(delegate, this, null, null);
332         } catch (JMException JavaDoc me) {
333             if (logger.isLoggable(BasicLevel.DEBUG)) {
334                 logger.log(BasicLevel.DEBUG,
335                         "JMX service could not be added as notification listener for MBeanServerNotifications "
336                                 + "related to the REGISTRATION or UNREGISTRETION of JOnAS management MBeans");
337             }
338         }
339         // Create data structures allowing to manage the servers in the domain
340
managedServersToConnectors = new HashMap JavaDoc();
341         managedServersToConnections = new HashMap JavaDoc();
342         managedServersToUrls = new HashMap JavaDoc();
343     }
344     /**
345      * Stop this service
346      */

347     public void doStop() {
348         try {
349             InitialContext JavaDoc ictx = new InitialContext JavaDoc();
350             ictx.unbind("RMIConnector_" + getJonasServerName());
351             ictx.close();
352
353             // Desactivates the connector server, that is, stops listening for client connections.
354
// Calling this method will also close all client connections that were made by this server.
355
// Being a potentialy slow operation, we keep it commented for the moment
356
for (int i = 0; i < connectorServers.length; i++) {
357                 connectorServers[i].stop();
358             }
359         } catch (Exception JavaDoc e) {
360             logger.log(BasicLevel.ERROR, "Cannot Unbind Jmx RMI Connector" + e);
361         }
362         // Unregister some MBeans
363
ObjectName JavaDoc domainOn = J2eeObjectName.J2EEDomain(getDomainName());
364         try {
365             getJmxServer().unregisterMBean(domainOn);
366         } catch (Exception JavaDoc e) {
367             logger.log(BasicLevel.INFO, "Cannot unregister JEEDomain MBean:" + domainOn.toString());
368         }
369         ObjectName JavaDoc serverOn = J2eeObjectName.J2EEServer(getDomainName(), getJonasServerName());
370         try {
371             getJmxServer().unregisterMBean(serverOn);
372         } catch (Exception JavaDoc e) {
373             logger.log(BasicLevel.INFO, "Cannot unregister JEEServer MBean:" + serverOn.toString());
374         }
375         // Remove internal references to the MBeanServer.
376
releaseJmxServer();
377
378         if (logger.isLoggable(BasicLevel.DEBUG)) {
379             logger.log(BasicLevel.DEBUG, "JMX Service stopped");
380         }
381     }
382
383
384     /**
385      *
386      * @return The actual adresses on which listen the created connector servers
387      */

388     public JMXServiceURL JavaDoc[] getConnectorServerURLs() {
389         return this.connectorServerURLs;
390     }
391
392     /**
393      * Treat REGISTRATION/UNREGISTRATION MBeanServerNotification generated for "management" MBeans
394      * Treat also notifications generated by Enroller MBean
395      * @param notification received notification
396      * @param handback received handback
397      */

398     public void handleNotification(Notification JavaDoc notification, Object JavaDoc handback) {
399         if (notification instanceof MBeanServerNotification JavaDoc) {
400             String JavaDoc type = notification.getType();
401             // ObjectName of the MBean that caused the notification
402
ObjectName JavaDoc registeredOn = ((MBeanServerNotification JavaDoc) notification).getMBeanName();
403             String JavaDoc name = registeredOn.getKeyProperty("name");
404             // The names below are defined in JonasObjectName class
405
if ((name != null) && (name.equals("discoveryEnroller") || name.equals("discoveryClient"))) {
406                 if (type.equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
407                     try {
408                         // register myself as listener of notifications emitted by the Enroller or DiscoveryClient MBean
409
getJmxServer().addNotificationListener(registeredOn, this, null, null);
410                         if (loggerDomain.isLoggable(BasicLevel.DEBUG)) {
411                             loggerDomain.log(BasicLevel.DEBUG, "J2EEDomain (this) registered as listener to notifs emitted by " + registeredOn);
412                         }
413                     } catch (InstanceNotFoundException JavaDoc e) {
414                         // TODO Auto-generated catch block
415
e.printStackTrace();
416                     }
417                 }
418                 if (type.equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
419                     try {
420                         // unregister myself as listener of notifications emitted by the Enroller or DiscoveryClient MBean
421
getJmxServer().removeNotificationListener(registeredOn, this);
422                         if (loggerDomain.isLoggable(BasicLevel.DEBUG)) {
423                             loggerDomain.log(BasicLevel.DEBUG, "J2EEDomain (this) removed listener for notifs emitted by " + registeredOn);
424                         }
425                     } catch (InstanceNotFoundException JavaDoc e) {
426                         // TODO Auto-generated catch block
427
e.printStackTrace();
428                     } catch (ListenerNotFoundException JavaDoc e) {
429                         // TODO Auto-generated catch block
430
e.printStackTrace();
431                     }
432                 }
433             }
434         } else {
435             // Tread discovery notification
436
String JavaDoc type = notification.getType();
437             String JavaDoc message = notification.getMessage();
438             DiscEvent userData = (DiscEvent) notification.getUserData();
439             String JavaDoc source = ((ObjectName JavaDoc) notification.getSource()).toString();
440             String JavaDoc state = userData.getState();
441             if (loggerDomain.isLoggable(BasicLevel.DEBUG)) {
442                 loggerDomain.log(BasicLevel.DEBUG, "Treat notification:");
443                 loggerDomain.log(BasicLevel.DEBUG, "- source: " + source);
444                 loggerDomain.log(BasicLevel.DEBUG, "- type: " + type);
445                 loggerDomain.log(BasicLevel.DEBUG, "- data: ");
446                 loggerDomain.log(BasicLevel.DEBUG, "--- state: " + state);
447                 loggerDomain.log(BasicLevel.DEBUG, "--- serverName : " + userData.getServerName());
448                 loggerDomain.log(BasicLevel.DEBUG, "--- domainName : " + userData.getDomainName());
449                 if (userData.getConnectorURL() != null) {
450                     String JavaDoc[] urls = userData.getConnectorURL();
451                     for (int i = 0; i < urls.length; i++) {
452                         loggerDomain.log(BasicLevel.DEBUG, "--- urls : " + urls[i]);
453                     }
454                 }
455                 loggerDomain.log(BasicLevel.DEBUG, "");
456             }
457             if (state.equals(DiscEvent.RUNNING)) {
458                 String JavaDoc[] urls = userData.getConnectorURL();
459                 for (int i = 0; i < urls.length; i++) {
460                     addServer(userData.getDomainName(), userData.getServerName(), urls[i]);
461                 }
462             } else if (state.equals(DiscEvent.STOPPING)) {
463                 removeServer(userData.getDomainName(), userData.getServerName());
464             }
465         }
466     }
467     /**
468      * Add a JOnAS server in the management domain in order
469      * update the management domain configuration.
470      *
471      * @param domainName name of the management domain the server belongs to
472      * @param serverName server name
473      * @param connectorServerURL connector server url
474      */

475     public void addServer(String JavaDoc domainName, String JavaDoc serverName, String JavaDoc connectorServerURL) {
476         if (loggerDomain.isLoggable(BasicLevel.DEBUG)) {
477             loggerDomain.log(BasicLevel.DEBUG, "domain name: " + domainName + ", server name: " + serverName + ", url: " + connectorServerURL);
478         }
479         if (domainName.equals(getDomainName())) {
480             // Server that belongs to the current management domain
481
if (!managedServersToUrls.containsKey(serverName)) {
482                 // Unknown server, try to create a connection for it
483
boolean created;
484                 try {
485                     created = createConnection(serverName, connectorServerURL);
486                 } catch (Exception JavaDoc e) {
487                     created = false;
488                     if (loggerDomain.isLoggable(BasicLevel.WARN)) {
489                         loggerDomain.log(BasicLevel.WARN, "Could not create JMX connection for server " + serverName , e);
490                     }
491                 }
492                 if (created) {
493                     ArrayList JavaDoc urls = new ArrayList JavaDoc();
494                     urls.add(connectorServerURL);
495                     managedServersToUrls.put(serverName, urls);
496                 }
497             } // Else :
498
// This server is already known, and has a working connection.
499
} else {
500             if (loggerDomain.isLoggable(BasicLevel.WARN)) {
501                 loggerDomain.log(BasicLevel.WARN, "The server named " + serverName + " was not started in the management domain "
502                         + getDomainName() + ", but in management domain " + domainName);
503             }
504         }
505     }
506
507     /**
508      * Create a MBeanServer connection using the provided url for the provided server
509      * @param serverName the name of the server to be connnected to
510      * @param connectorServerURL the url used to construct connection address
511      * @return true if a connection created
512      * @throws NamingException
513      * @throws IOException
514      */

515     private boolean createConnection(String JavaDoc serverName, String JavaDoc connectorServerURL) throws NamingException JavaDoc, IOException JavaDoc {
516         boolean created = false;
517         MBeanServerConnection JavaDoc connection;
518         // create a connector client for the connector server at the given url
519
JMXConnector JavaDoc connector = null;
520         JMXServiceURL JavaDoc url = new JMXServiceURL JavaDoc(connectorServerURL);
521         Map JavaDoc env = null;
522         if (url.getProtocol().equals("iiop")) {
523             env = new HashMap JavaDoc();
524             env.put("java.naming.corba.orb", new InitialContext JavaDoc().lookup("java:comp/ORB"));
525         }
526         connector = JMXConnectorFactory.newJMXConnector(url, env);
527         connector.connect(env);
528         connection = connector.getMBeanServerConnection();
529         if (connection != null) {
530             // OK, connection was established to the connector server.
531
testConnection(connection, serverName);
532             if (managedServersToConnections.containsKey(serverName)) {
533                 // A connection already exists.
534
// We have the following possibilities:
535
// - ignore this connection (close it), so continue to use the old one
536
// - replace the old one by the new one (close the old)
537
// - keep several connections
538
//
539
// Currently we keep only one connection, the new one (second approach)
540
JMXConnector JavaDoc oldConnector = (JMXConnector JavaDoc) managedServersToConnectors.get(serverName);
541                 try {
542                     oldConnector.close();
543                 } catch (IOException JavaDoc e1) {
544                 }
545             }
546             managedServersToConnections.put(serverName, connection);
547             managedServersToConnectors.put(serverName, connector);
548             created = true;
549             loggerDomain.log(BasicLevel.INFO, "MBeanServerConnection created for connecting to server " + serverName + " using URL: " + connectorServerURL);
550         } else {
551             if (connector != null) {
552                 try {
553                     connector.close();
554                 } catch (IOException JavaDoc e1) {
555                 }
556             }
557         }
558         return created;
559     }
560
561     private boolean testConnection(MBeanServerConnection JavaDoc connection, String JavaDoc serverName) {
562         boolean ok = false;
563         try {
564             Integer JavaDoc nb = connection.getMBeanCount();
565             /*
566             System.out.println("IN TEST connection: got " + nb.toString() + " MBeans in the JMX server of JOnAS server " + serverName);
567             */

568             ok = true;
569         } catch (IOException JavaDoc ioe) {
570             ioe.printStackTrace();
571         }
572         return ok;
573     }
574
575     /**
576      * Add a JOnAS server in the management domain
577      * @param domainName name of the management domain the server belongs
578      * @param serverName server name
579      */

580     public void removeServer(String JavaDoc domainName, String JavaDoc serverName) {
581         if (domainName.equals(getDomainName())) {
582             // Server thet belongs to the current management domain
583

584             managedServersToConnections.remove(serverName);
585             JMXConnector JavaDoc connector = (JMXConnector JavaDoc) managedServersToConnectors.remove(serverName);
586             if (connector != null) {
587             try {
588                 connector.close();
589             } catch (IOException JavaDoc e1) {
590             }
591             }
592             managedServersToUrls.remove(serverName);
593         } else {
594             if (loggerDomain.isLoggable(BasicLevel.WARN)) {
595                 loggerDomain.log(BasicLevel.WARN, "The server named " + serverName + " was not started in the management domain "
596                         + getDomainName() + ", but in management domain " + domainName);
597             }
598         }
599     }
600     /**
601      * Return a connection to the JMX serverver of a given JOnAS server
602      * @param serverName The name of the server a connection to its JMX server its needed
603      * @return A connection to that server's JMX server
604      */

605     public MBeanServerConnection JavaDoc getServerConnection(String JavaDoc serverName) {
606         return (MBeanServerConnection JavaDoc) managedServersToConnections.get(serverName);
607     }
608 }
609
Popular Tags