KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > meta > MBeanRegistry


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * $Id: MBeanRegistry.java,v 1.6 2006/03/12 01:26:57 jluehe Exp $
26  * @author: alexkrav
27  *
28  * $Log: MBeanRegistry.java,v $
29  * Revision 1.6 2006/03/12 01:26:57 jluehe
30  * Renamed AS's org.apache.commons.* to com.sun.org.apache.commons.*, to avoid collisions with org.apache.commons.* packages bundled by webapps.
31  *
32  * Tests run: QL, Servlet TCK
33  *
34  * Revision 1.5 2005/12/25 03:47:37 tcfujii
35  * Updated copyright text and year.
36  *
37  * Revision 1.4 2005/11/03 16:32:00 kravtch
38  * Bug #6325219
39  * Never-called constructor removed from MBeanRegistry.
40  * Submitted by: kravtch
41  * Reviewed by: Shreedhar
42  * Affected modules admin/core/admin
43  * Tests passed: QLT/EE + devtests
44  * -----
45  *
46  * Revision 1.3 2005/08/16 22:19:31 kravtch
47  * M3: 1. ConfigMBeans: Support for generic getXXXNamesList() operation (request from management-rules).
48  * 2. MBeanRegistry: support for getElementPrintName() to provide readable element's description for validator's messages
49  * Submitted by: kravtch
50  * Reviewed by: Shreedhar
51  * Affected modules admin-core/admin
52  * Tests passed: QLT/EE + devtests
53  *
54  * Revision 1.2 2005/06/27 21:19:44 tcfujii
55  * Issue number: CDDL header updates.
56  *
57  * Revision 1.1.1.1 2005/05/27 22:52:02 dpatil
58  * GlassFish first drop
59  *
60  * Revision 1.23 2004/11/14 07:04:21 tcfujii
61  * Updated copyright text and/or year.
62  *
63  * Revision 1.22 2004/09/14 00:55:59 kravtch
64  * Patch added to MBeanRegistry: every time when new config element is addeded - config context of the root element will be propagated to its children
65  * Bug #6171788
66  * Reviewer: Sridatta
67  * Tests passed: QLT +EE
68  *
69  * Revision 1.21 2004/04/21 18:36:38 kravtch
70  * Reviewer: Sridatta
71  * Mbean registration is added for new ConfigBean along with dottedNameRegistration
72  *
73  * Revision 1.20 2004/04/05 16:44:05 kravtch
74  * admin/meta/AdminConfigEventListener: new configcontext listener's code
75  * This listener is for synchronization of ConfigBeans changes with both MBeans and dotted-name spaces.
76  * admin/meta/MBeanRegistry: added methods (adoptConfigBeanDelete/Add) implementing beans ajustment
77  * admin/config/BaseConfigMBean: calls from MBean's postRegister/unregister methods to dotted-name-manager is commented out.
78  *
79  * Reviewer: Sridatta
80  * Tests Passed: QuickLook + UnitTest
81  *
82  * Revision 1.19 2004/02/20 03:56:14 qouyang
83  *
84  *
85  * First pass at code merge.
86  *
87  * Details for the merge will be published at:
88  * http://javaweb.sfbay.sun.com/~qouyang/workspace/PE8FCSMerge/02202004/
89  *
90  * Revision 1.16.4.3 2004/02/02 07:25:19 tcfujii
91  * Copyright updates notices; reviewer: Tony Ng
92  *
93  * Revision 1.16.4.2 2003/12/23 01:51:46 kravtch
94  * Bug #4959186
95  * Reviewer: Sridatta
96  * Checked in PE8FCS_BRANCH
97  * (1) admin/admin-core/admin-cli/admin-gui/appserv-core/assembly-tool: switch to new domain name "ias:" -> "com.sun.appserv"
98  * (2) admin-core and admin-cli: switch to "dashed" attribute names
99  * (3) admin-core: support both "dashed"/"underscored" names for get/setAttributes
100  * (4) admin-gui: hook for reverse converting attribute names (temporary hack);
101  *
102  * Revision 1.16.4.1 2003/12/01 21:52:39 kravtch
103  * Bug #4939964
104  * Reviewer: Sridatta
105  * admin.config.ManagedConfigBean.createChildByType() now analyzes registryEntries.AttributeInfo for each "empty" valued attribute (similar to setAttribute(), but could not use MBeanAttributeInfo because MBean is not exists yet). If "emptyValueAllowed" field in registrEntry.AttributeInfo is not "true", then "empty" attribute will be ignored.
106  * Revision 1.16 2003/09/09 22:31:04 kravtch
107  * Bug: #4919291
108  * Reviewer: Sridatta
109  * commons-modeler's manageMBean is subclassed. Subclassing constructor removes requiered for commons-modeler "modeler_type" attribute.
110  *
111  * Revision 1.15 2003/09/05 06:06:10 kravtch
112  * Bug #4915176
113  * Reviewer: Sridatta
114  * - new custom mbean - DomainMBean implemented public AttributeList getDefaultCustomProperties(String mbeanTypeName, AttributeList attributeList) to fulfill the reques;
115  * - descriptor file is updated (classname for this mbean added)
116  * - mandatory getDefaultCustomProperties() removed from all MBeanInfos;
117  * - CLI name for http-listener.ssl repared in descriptors file;
118  * - non-neccessary logs suppressed;
119  *
120  * Revision 1.14 2003/09/04 05:53:49 kravtch
121  * bugs #4896268 and #4913653
122  * Reviewer: Sridatta
123  * -AuthRealmMbean's getFielRealm is chaged from creating of the new FileRealm object to gettting it from security pool - Realm.getInstance(name) with casting result to FileRealm.
124  * This approach will work only for PE because DAS and instance have the same auth-realms.
125  * -AdminContext expanded by two new methods getAdminMBeanResourcUrl() and getRuntimeMBeanResourcUrl() which used by MBeanRegistryFactory for initialization admin and runtime registries. So, they are become pluggable.
126  * -AdminContext also notifies MBeanRegistryFactory during its construction. So, AdminContext become "visible" to admin-core/admin classes.
127  * -Hardcoded output changed to appropriate logger calls.
128  *
129  * Revision 1.13 2003/08/26 05:51:48 kravtch
130  * ignore tailing slashes in XPath
131  * for matching with xpath template
132  * Reviewer: Ramakanth
133  *
134  * Revision 1.12 2003/08/16 21:33:05 kravtch
135  * Switch to logger for printing debug messages:
136  * System.out.printlns->_slogger.log(...)
137  *
138  * Revision 1.11 2003/08/16 03:06:25 sridatta
139  * correcting object name for dottednameregistry
140  *
141  * Revision 1.10 2003/08/15 23:08:28 kravtch
142  * DottedName Support (generation and call to manager)
143  * notifyRegisterMBean/UnregisterMBean are implemented;
144  * dotted name related opeartions are added to NaminDescriptor and NamingInfo
145  * removeChild support is added;
146  *
147  * Revision 1.9 2003/08/07 00:41:06 kravtch
148  * - new DTD related changes;
149  * - properties support added;
150  * - getDefaultAttributeValue() implemented for config MBeans;
151  * - merge Jsr77 and config activity in runtime mbeans;
152  *
153  * Revision 1.8 2003/07/29 18:59:35 kravtch
154  * MBeanRegistryEntry:
155  * - support for toFormatString();
156  * - instantiateMBean() method modified to instantiate runtime MBeans as well;
157  * MBeanRegistryFactory:
158  * - fixed bug in getRuntimeRegistry();
159  * MBeanNamingInfo:
160  * - less strict requirements for parm_list_array size in constructor (can be more then needed);
161  * BaseRuntimeMBean:
162  * - exception ClassCastException("Managed resource is not a Jsr77ModelBean") handling;
163  * ManagedJsr77MdlBean:
164  * - call managed bean bug fixed ( getDeclaredMethod()->getMethod())
165  * admin/dtds/runtime-mbeans-descriptors.xml - modified to represent new runtime mbeans;
166  *
167  * Revision 1.7 2003/06/25 20:03:40 kravtch
168  * 1. java file headers modified
169  * 2. properties handling api is added
170  * 3. fixed bug for xpathes containing special symbols;
171  * 4. new testcases added for jdbc-resource
172  * 5. introspector modified by not including base classes operations;
173  *
174  *
175 */

176
177 package com.sun.enterprise.admin.meta;
178
179 import java.io.InputStream JavaDoc;
180 import java.util.Hashtable JavaDoc;
181 import java.util.TreeMap JavaDoc;
182 import java.util.Iterator JavaDoc;
183 import java.util.Set JavaDoc;
184 import java.util.ArrayList JavaDoc;
185
186 // Logging
187
import java.util.logging.Logger JavaDoc;
188 import java.util.logging.Level JavaDoc;
189 import com.sun.logging.LogDomains;
190
191 import javax.management.MBeanServer JavaDoc;
192 import javax.management.DynamicMBean JavaDoc;
193 import javax.management.ObjectName JavaDoc;
194 import javax.management.Descriptor JavaDoc;
195 import javax.management.MBeanServerFactory JavaDoc;
196 import javax.management.MalformedObjectNameException JavaDoc;
197
198 import com.sun.org.apache.commons.modeler.ManagedBean;
199 import com.sun.org.apache.commons.modeler.Registry;
200 import com.sun.org.apache.commons.modeler.AttributeInfo;
201
202 import com.sun.enterprise.admin.meta.naming.MBeanNamingDescriptor;
203 import com.sun.enterprise.admin.meta.naming.MBeanNamingInfo;
204 import com.sun.enterprise.admin.meta.naming.MBeanNamingException;
205 import com.sun.enterprise.admin.meta.naming.MBeansNaming;
206
207 import com.sun.enterprise.admin.BaseAdminMBean;
208
209 import com.sun.enterprise.config.ConfigContext;
210 import com.sun.enterprise.config.ConfigException;
211 import com.sun.enterprise.config.ConfigBean;
212 import com.sun.enterprise.config.ConfigBeansFactory;
213 import com.sun.enterprise.config.serverbeans.ServerTags;
214 import com.sun.enterprise.config.serverbeans.ServerXPathHelper;
215 import com.sun.enterprise.config.ConfigContextEvent;
216
217 /**
218  * Provides naming support for Mbeans
219  */

220 public class MBeanRegistry //extends MBeansNaming
221
{
222     private final static String JavaDoc MSG_FINDREGISTRYENTRY_FAILED = "mbean.config.findregistryentry_failed";
223
224     // Logging
225
static protected Logger JavaDoc _sLogger = LogDomains.getLogger(LogDomains.ADMIN_LOGGER);
226
227     private MBeanRegistryEntry[] entries = null;
228     
229     public String JavaDoc toString()
230     {
231         String JavaDoc str = "MBeanRegistry("+entries.length+" entries):\n";
232         for(int i=0; i<entries.length; i++)
233         {
234             str = str + entries[i].toString();
235         }
236         return str;
237     }
238
239     public String JavaDoc toFormatString()
240     {
241         String JavaDoc str = "MBeanRegistry("+entries.length+" entries):\n";
242         for(int i=0; i<entries.length; i++)
243         {
244             str = str + entries[i].toFormatString();
245         }
246         return str;
247     }
248
249     //**************************************************************************
250
private class MyRegistry extends Registry
251     {
252         public MyRegistry()
253         {
254             super();
255         }
256         
257     }
258
259     
260     //**************************************************************************
261
private class MyManagedBean extends ManagedBean
262     {
263         public MyManagedBean(ManagedBean mb)
264         {
265             super();
266             AttributeInfo attrs[] = mb.getAttributes();
267             if(attrs.length>0 && "modelerType".equals(attrs[0].getName()))
268             {
269                 attributes = new AttributeInfo[attrs.length-1];
270                 for(int i=1; i<attrs.length; i++)
271                     attributes[i-1]=attrs[i];
272             }
273             else
274                 attributes = attrs;
275             className = mb.getClassName();
276             constructors = mb.getConstructors();
277             description = mb.getDescription();
278             domain = mb.getDomain();
279             group = mb.getGroup();
280             name = mb.getName();
281             fields = mb.getFields();
282             notifications = mb.getNotifications();
283             operations = mb.getOperations();
284             type = mb.getType();
285         }
286         
287     }
288
289   
290     //**************************************************************************
291
public void loadMBeanRegistry(InputStream JavaDoc stream) throws MBeanMetaException,MBeanNamingException,ClassNotFoundException JavaDoc
292     {
293         MyRegistry registry = new MyRegistry();
294         try {
295             registry.loadDescriptors("MbeansDescriptorsDOMSource", stream, null);
296         } catch (Exception JavaDoc e)
297         {
298             throw new MBeanMetaException(e.getMessage());
299         }
300         // naming init
301
String JavaDoc[] names = registry.findManagedBeans();
302         entries = new MBeanRegistryEntry[names.length]; //loose the prev ?
303
for(int i=0; i<names.length; i++)
304         {
305             entries[i] = new MBeanRegistryEntry(new MyManagedBean(registry.findManagedBean(names[i])));
306         }
307 // MBeansNaming.initMBeanNaming();
308

309     }
310     
311     //**************************************************************************
312
public MBeanRegistryEntry findMBeanRegistryEntry(ObjectName JavaDoc objectName)
313     {
314         try
315         {
316             Hashtable JavaDoc ht = objectName.getKeyPropertyList();
317             ht.put(":",objectName.getDomain()); //add domain name pseudo pair
318

319             for(int i=0; i<entries.length; i++)
320             {
321                 if(entries[i]!=null && entries[i].isObjectNamePatternMatch(ht))
322                     return entries[i];
323             }
324         }
325         catch (Exception JavaDoc e)
326         {
327             _sLogger.log(Level.FINE, MSG_FINDREGISTRYENTRY_FAILED, e);
328         }
329         return null;
330     }
331     //**************************************************************************
332
public MBeanRegistryEntry findMBeanRegistryEntryByType(String JavaDoc type)
333     {
334         for(int i=0; i<entries.length; i++)
335         {
336             if(entries[i]!=null && entries[i].getName().equals(type))
337                 return entries[i];
338         }
339         return null;
340     }
341     
342     //**************************************************************************
343
public MBeanRegistryEntry findMBeanRegistryEntryByXPath(String JavaDoc xpath)
344     {
345         if(xpath!=null)
346             while(xpath.length()>1 && xpath.endsWith("/"))
347                 xpath = xpath.substring(0, xpath.length()-1);
348         Object JavaDoc[] tokens = MBeanNamingDescriptor.getXPathTokens(xpath);
349  
350         for(int i=0; i<entries.length; i++)
351         {
352             if(entries[i].getNamingDescriptor().isXpathTokensMatch(tokens))
353                 return entries[i];
354         }
355         return null;
356     }
357
358     //**************************************************************************
359
public MBeanRegistryEntry findMBeanRegistryEntryByXPathPattern(String JavaDoc patternPrefix)
360     {
361         // bring prefix into accord of inner naming descriptor's pattern style (double apostrophies)
362
patternPrefix = MBeanNamingDescriptor.XPATH_TO_MASK(patternPrefix);
363         int len = patternPrefix.length();
364         String JavaDoc pattern;
365         //enum entries to find matching pattern
366
for(int i=0; i<entries.length; i++)
367         {
368             pattern = entries[i].namingDescriptor.getXPathPattern();
369             if( pattern!= null &&
370                 pattern.startsWith(patternPrefix) &&
371                 (pattern.length()==len || pattern.indexOf('/', len)<0 ) )
372                return entries[i];
373         }
374         return null;
375     }
376
377     //**************************************************************************
378
public ObjectName JavaDoc getMbeanObjectName(String JavaDoc type, String JavaDoc[] location)
379     {
380         return getMbeanObjectName(findMBeanRegistryEntryByType(type), type, location);
381     }
382     
383     //**************************************************************************
384
private ObjectName JavaDoc getMbeanObjectName(MBeanRegistryEntry entry, String JavaDoc type, String JavaDoc[] location)
385     {
386  
387         if(entry!=null)
388         {
389             try {
390                 MBeanNamingInfo namingInfo = new MBeanNamingInfo(entry.getNamingDescriptor(), type, location);
391                 if(namingInfo!=null)
392                     return namingInfo.getObjectName();
393             } catch (Exception JavaDoc e)
394             {
395                 e.printStackTrace();
396             }
397         }
398         return null;
399     }
400
401     //**************************************************************************
402
public BaseAdminMBean instantiateConfigMBean( ObjectName JavaDoc objectName, Object JavaDoc managedResource) throws Exception JavaDoc
403     {
404         return instantiateConfigMBean( objectName, managedResource, null);
405     }
406     
407     //**************************************************************************
408
public BaseAdminMBean instantiateConfigMBean( ObjectName JavaDoc objectName, Object JavaDoc managedResource, ConfigContext ctx) throws Exception JavaDoc
409     {
410         MBeanRegistryEntry entry = findMBeanRegistryEntry(objectName);
411         if(entry!=null)
412         {
413             MBeanNamingDescriptor descr = entry.getNamingDescriptor();
414             return entry.instantiateMBean(objectName, managedResource, ctx);
415         }
416         return null;
417     }
418
419     //**************************************************************************
420
public BaseAdminMBean instantiateMBean( String JavaDoc type, String JavaDoc[] location) throws Exception JavaDoc
421     {
422         return instantiateMBean( type, location, null, null);
423     }
424     //**************************************************************************
425
public BaseAdminMBean instantiateMBean( String JavaDoc type, String JavaDoc[] location, Object JavaDoc managedResource, ConfigContext ctx) throws Exception JavaDoc
426     {
427         return instantiateMBean( type, location, managedResource, ctx, false);
428     }
429
430     //**************************************************************************
431
public MBeanNamingInfo getMBeanNamingInfo(ObjectName JavaDoc objectName) throws Exception JavaDoc
432     {
433         MBeanRegistryEntry entry = this.findMBeanRegistryEntry(objectName);
434         return new MBeanNamingInfo(entry.getNamingDescriptor(), objectName);
435     }
436     //**************************************************************************
437
// this method is called called during MBean Registration
438
// it notifies the dotted name manager about new MBean appearing
439
// registering correspondent dotted names
440
public void notifyRegisterMBean(ObjectName JavaDoc objectName, ConfigContext ctx)
441     {
442         try {
443             MBeanNamingInfo namingInfo = getMBeanNamingInfo(objectName);
444             ArrayList JavaDoc arr = getValidDottedNames(namingInfo);
445             if(arr!=null)
446                 for(int i=0; i<arr.size(); i++) //enumerate all dotted names aliases
447
addDottedName((String JavaDoc)arr.get(i), namingInfo.getObjectName());
448             //FIXME: only if no XPath -> notifying Lloyd's MBean
449
} catch (Exception JavaDoc e)
450         {}
451     }
452     
453     //**************************************************************************
454
public void notifyUnregisterMBean(ObjectName JavaDoc objectName, ConfigContext ctx)
455     {
456         try {
457             MBeanNamingInfo namingInfo = getMBeanNamingInfo(objectName);
458             ConfigBean bean = null;
459             try
460             {
461                 bean = (ConfigBean)ConfigBeansFactory.getConfigBeanByXPath(ctx, namingInfo.getXPath());
462             }
463             catch (Exception JavaDoc e)
464             {}
465             if(bean==null)
466                removeDottedName(objectName);
467         } catch (Exception JavaDoc e)
468         {}
469     }
470     
471     //**************************************************************************
472
public void generateAndRegisterAllDottedNames(ConfigContext ctx, String JavaDoc domainName) throws MBeanMetaException
473     {
474         ConfigBean bean = null;
475         try
476         {
477             bean = (ConfigBean)ConfigBeansFactory.getConfigBeanByXPath(ctx, "/domain");
478             registerDottedName(bean, domainName);
479         }
480         catch (Exception JavaDoc e)
481         {
482             throw new MBeanMetaException("DottedNamesRegistration: Could not get '/domain' ConfigMBean");
483         }
484     }
485
486     /**
487      * This method can be used to register all config mbeans that are
488      * available in the system. It recursively descends the configbean tree
489      * and instantiates the mbean based on the descriptor file and
490      * registers the mbeans. If a configbean is null, the mbean is skipped
491      * and recursion is continued. Also, if the mbean is already created, then
492      * the InstanceAlreadyException is ignored (or, alternatively, the
493      * registration is not even attempted). No exception is thrown from the
494      * recursive method and is a best effort solution. The only exception
495      * thrown is when domain bean cannot be obtained.
496      *
497      * @param ctx ConfigContext used for creating config mbeans
498      * @param domainName domainName used for registering the mbeans
499      *
500      * @exception MBeanMetaException. ConfigException is wrapped as
501      * MBeanMetaException when domain bean is not obtained and the
502      * ConfigException is also chained.
503      *
504      * @see generateAndRegisterAllDottedNames
505      */

506     public void instantiateAndRegisterAllConfigMBeans(
507                                 ConfigContext ctx,
508                                 String JavaDoc domainName)
509                                 throws MBeanMetaException
510     {
511         ConfigBean bean = null;
512         try
513         {
514             bean = (ConfigBean)ConfigBeansFactory.getConfigBeanByXPath(ctx,
515                                                 ServerXPathHelper.XPATH_DOMAIN);
516         }
517         catch (ConfigException e)
518         {
519             _sLogger.log(Level.FINEST,
520                 "Exception during Instantiating All Config MBeans in MBeanRegistry", e);
521             throw new MBeanMetaException
522                 ("ConfigException in getting Domain bean from config context", e);
523         }
524         instantiateAndRegisterConfigMBeans(bean, domainName);
525         _sLogger.log(Level.FINEST,
526             "Instantiated All Config MBeans in MBeanRegistry Successfully");
527     }
528     
529     
530     //****************************************************************************************************
531
private String JavaDoc getFirstValidDottedName(MBeanNamingInfo namingInfo)
532     {
533         ArrayList JavaDoc arr = getValidDottedNames(namingInfo);
534         if(arr!=null && arr.size()>0)
535             return (String JavaDoc)arr.get(0);
536         return null;
537     }
538     
539     //****************************************************************************************************
540
private ArrayList JavaDoc getValidDottedNames(MBeanNamingInfo namingInfo)
541     {
542         ArrayList JavaDoc arr = new ArrayList JavaDoc();
543         try {
544             String JavaDoc [] dottedNames = namingInfo.getDottedNames();
545             for(int i=0; i<dottedNames.length; i++)
546             {
547                 if( dottedNames[i].length()>0 &&
548                     !dottedNames[i].startsWith("@"))
549                     arr.add(dottedNames[i]);
550             }
551         } catch (Exception JavaDoc e)
552         {}
553         return arr;
554     }
555     //****************************************************************************************************
556
// registers dotted name(s) for given ConfigBean
557
// supports multiple aliases registration (not supported yet by dotted names framework)
558
private void registerDottedName(ConfigBean bean, String JavaDoc domainName)
559     {
560         if(bean==null)
561             return;
562         String JavaDoc xpath = bean.getAbsoluteXPath("");
563         try
564         {
565             MBeanNamingInfo namingInfo = getNamingInfoForConfigBean(bean, domainName);
566             ObjectName JavaDoc objectName = namingInfo.getObjectName();
567             ArrayList JavaDoc arr = getValidDottedNames(namingInfo);
568             if(arr!=null)
569                 for(int i=0; i<arr.size(); i++) //enum aliases
570
{
571                     // register dotted name/alias
572
addDottedName((String JavaDoc)arr.get(i), objectName);
573                 }
574        }
575         catch(Exception JavaDoc e)
576         {
577             if(xpath!=null && xpath.indexOf("/"+ServerTags.ELEMENT_PROPERTY+"[")==0)
578             {
579                 _sLogger.log(Level.FINE,"---- Exception for xpath="+xpath, e);
580             }
581         }
582         try
583         {
584             ConfigBean[] beans = bean.getAllChildBeans();
585             for(int i=0; i<beans.length; i++)
586             {
587                 registerDottedName(beans[i], domainName);
588             }
589         }
590         catch(Exception JavaDoc e)
591         {
592         }
593     }
594
595     //****************************************************************************************************
596

597     /**
598      * A recursive method to register all mbeans from the bean specified
599      * Step 1, Get mbean for that bean. Step 2, Find all children for bean
600      * Step 3, call this method for each bean
601      *
602      * If bean is null, return silently. This method is designed to instantiate
603      * all possible mbeans without throwing any exceptions--a best effort
604      * solution.
605      */

606     private void instantiateAndRegisterConfigMBeans(ConfigBean bean, String JavaDoc domainName)
607     {
608         if(bean == null)
609             return;
610         String JavaDoc xpath = bean.getAbsoluteXPath("");
611         ConfigContext ctx = bean.getConfigContext();
612         try
613         {
614             ObjectName JavaDoc objectName = getObjectNameForConfigBean(bean, domainName);
615             if(objectName!=null)
616             {
617                 MBeanServer JavaDoc mServer = (MBeanServer JavaDoc)MBeanServerFactory.findMBeanServer(null).get(0);
618                 if (!mServer.isRegistered(objectName))
619                 {
620 //register here
621
BaseAdminMBean mbean = instantiateConfigMBean(objectName, null, ctx) ;
622                     registerMBean(mbean, objectName);
623                 }
624             }
625         }
626         catch(Exception JavaDoc e)
627         {
628             if(xpath!=null && xpath.indexOf("/"+ServerTags.ELEMENT_PROPERTY+"[")==0)
629             {
630                 _sLogger.log(Level.FINEST,"---- Exception for xpath="+xpath, e);
631             }
632         }
633         try
634         {
635             ConfigBean[] beans = bean.getAllChildBeans();
636             for(int i=0; i<beans.length; i++)
637             {
638                 if(beans[i]!=null && beans[i].getConfigContext()==null)
639                 { //temporary patch for bug #6171788
640
beans[i].setConfigContext(ctx);
641                 }
642                 
643                 try {
644                     instantiateAndRegisterConfigMBeans(beans[i], domainName);
645                 } catch(Exception JavaDoc e1) {
646                     //ignore
647
_sLogger.log(Level.FINEST,
648                         "Exception in instantiateAndRegisterConfigMBeans:", e1);
649                 }
650             }
651         }
652         catch(Exception JavaDoc e)
653         {
654              _sLogger.log(Level.FINEST,
655                         "Exception in instantiateAndRegisterConfigMBeans:", e);
656         }
657     }
658     
659     /**
660      * Note the check for isRegistered(). This is to prevent
661      * calling of preRegister in registerMBean. There can
662      * potentially be infinite loop in the case where
663      * preRegister() goes queryNames or queryMBeans which inturn
664      * will call registerMBeans
665      *
666      * We need to silently move on when InstanceAlreadyException
667      * is thrown anyway. This does not change functionality in
668      * that sense.
669      */

670     private void registerMBean(BaseAdminMBean mbean, ObjectName JavaDoc name)
671                                         throws Exception JavaDoc {
672         MBeanServer JavaDoc mServer = (MBeanServer JavaDoc)MBeanServerFactory.findMBeanServer(null).get(0);
673         if (!mServer.isRegistered(name)) {
674             mServer.registerMBean(mbean, name);
675         }
676     }
677     //****************************************************************************************************
678
private static final ObjectName JavaDoc REGISTRATION_MBEAN_OBJECTNAME = getDottedRegMBeanName();
679     private static final String JavaDoc REGISTRATION_OPERATION_NAME = "add";
680     private static final String JavaDoc UNREGISTRATION_OPERATION_NAME = "remove";
681     //****************************************************************************************************
682
private static ObjectName JavaDoc getDottedRegMBeanName()
683     {
684         try {
685             return new ObjectName JavaDoc("com.sun.appserv:name=dotted-name-registry,type=dotted-name-support"); //CHANGE_ME
686
}
687         catch (Exception JavaDoc e)
688         {
689             e.printStackTrace();
690         }
691         return null;
692     }
693     //****************************************************************************************************
694
private void addDottedName(String JavaDoc dottedName, ObjectName JavaDoc objectName) throws Exception JavaDoc
695     {
696         _sLogger.log(Level.FINE, "******regDottedName******* "+dottedName +" ObjectName="+objectName);
697         MBeanServer JavaDoc mbeanServer = (MBeanServer JavaDoc)MBeanServerFactory.findMBeanServer(null).get(0);
698         mbeanServer.invoke(REGISTRATION_MBEAN_OBJECTNAME, REGISTRATION_OPERATION_NAME,
699                        new Object JavaDoc[]{dottedName, objectName},
700                        new String JavaDoc[]{dottedName.getClass().getName(), objectName.getClass().getName()});
701     }
702     //****************************************************************************************************
703
private void removeDottedName(ObjectName JavaDoc objectName) throws Exception JavaDoc
704     {
705         _sLogger.log(Level.FINE, "******unregDottedName******* for ObjectName="+objectName);
706         MBeanServer JavaDoc mbeanServer = (MBeanServer JavaDoc)MBeanServerFactory.findMBeanServer(null).get(0);
707         mbeanServer.invoke(REGISTRATION_MBEAN_OBJECTNAME, UNREGISTRATION_OPERATION_NAME,
708                        new Object JavaDoc[]{objectName},
709                        new String JavaDoc[]{objectName.getClass().getName()});
710     }
711     //**************************************************************************
712
public BaseAdminMBean instantiateMBean( String JavaDoc type, String JavaDoc[] location, Object JavaDoc managedResource, ConfigContext ctx, boolean bRegister) throws Exception JavaDoc
713     {
714         MBeanRegistryEntry entry = findMBeanRegistryEntryByType(type);
715         BaseAdminMBean mbean = null;
716         if(entry!=null)
717         {
718             mbean = entry.instantiateMBean(type, location, managedResource, location[0], ctx);
719             if(bRegister && mbean!=null)
720             {
721                 ObjectName JavaDoc objectName = getMbeanObjectName(entry, type, location);
722                 if(objectName!=null)
723                 {
724                     registerMBean(mbean, objectName);
725                 }
726             }
727         }
728         return mbean;
729     }
730 /* //SORT entries
731     // BY xpath
732     //**************************************************************************
733     public void sortRegistryEntriesByXpath()
734     {
735         // veeery slooow
736         ArrayList list = new ArrayList();
737         for(int i=0; i<entries.length; i++)
738         {
739             for(int j=0; j<list.size(); j++)
740             {
741                 if(entries[i].getNamingDescriptor().getXPathPattern().compareTo
742                    (((MBeanRegistryEntry)list.get[j]).getNamingDescriptor().getXPathPattern())<0)
743                 {
744                     list.add(j, entries[i]);
745                     break;
746                 }
747                 else
748                     if(j==list.size()-1)
749                         list.add(entries[i]);
750             }
751         }
752         entries = list.toArray(entries);
753     }
754
755  */

756     
757     public static final int SORT_BY_NAME = 0;
758     public static final int SORT_BY_XPATH = 1;
759     public void sortRegistryEntries(int sortType )
760     {
761         // veeery slooow
762
TreeMap JavaDoc map = new TreeMap JavaDoc();
763         String JavaDoc emptyKey = " ";
764         String JavaDoc key;
765         for(int i=0; i<entries.length; i++)
766         {
767             if(sortType==SORT_BY_XPATH)
768                 key = entries[i].getNamingDescriptor().getXPathPattern();
769             else
770                 key = entries[i].getName();
771             if(key==null || key.length()==0)
772             {
773                 key = emptyKey;
774                 emptyKey = emptyKey + " ";
775             }
776             map.put(key, entries[i]);
777         }
778         entries = (MBeanRegistryEntry[])map.values().toArray((Object JavaDoc[])(new MBeanRegistryEntry[0]));
779     }
780
781     //****************************************************************************************************
782
/*
783      * this method should be called from ConfigContextListener
784      * registers dotted-names correspondent to created ConfigBeans and its children
785     * (question: should we register created mbeans or just call dottedname registration?)
786      * @param bean added ConfigBean
787      * @param domainName ObjectName's domain name
788      * @param domainName
789      *
790      */

791    //****************************************************************************************************
792
public void adoptConfigBeanAdd(ConfigBean bean, String JavaDoc domainName)
793    {
794         _sLogger.log(Level.FINEST, "****** MBeanRegistry.adoptConfigBeanAddDelete->add element:"+bean);
795         instantiateAndRegisterConfigMBeans(bean, domainName);
796         registerDottedName(bean, domainName); //this one is already recursive
797
return;
798    }
799
800    //****************************************************************************************************
801
/*
802      * this method should be called from ConfigContextListener
803      * registers dotted-names and MBean correspondent to deleted ConfigBean and its children
804     * (question: should we register created mbeans or just call dottedname registration?)
805      * @param bean deleted ConfigBean
806      * @param domainName ObjectName's domain name
807      *
808      */

809    public void adoptConfigBeanDelete(ConfigBean bean, String JavaDoc domainName)
810    {
811         //delete only
812
// we need to unregister MBeans as well as unregister dotted name
813
_sLogger.log(Level.FINEST, "****** MBeanRegistry.adoptConfigBeanAddDelete->delete element"+bean);
814         ArrayList JavaDoc arr = new ArrayList JavaDoc();
815         collectChildrenObjectNames(bean, domainName, arr);
816         for(int i=0; i<arr.size(); i++)
817         {
818             ObjectName JavaDoc objectName = (ObjectName JavaDoc)arr.get(i);
819             if(objectName!=null)
820             {
821                 // first try to unregister dotted name
822
try
823                 {
824                     removeDottedName(objectName);
825                 }
826                 catch (Throwable JavaDoc t)
827                 {
828                     //this is ok, some elements has no dotted name
829
_sLogger.fine("!!!!!!!!!!!!!! Can not unregister dotted name for MBean: "+objectName);
830                 }
831                 
832                 // now, try to unregister MBean
833
try
834                 {
835                     MBeanServer JavaDoc server = (MBeanServer JavaDoc)MBeanServerFactory.findMBeanServer(null).get(0);
836                     if(server.isRegistered(objectName))
837                         server.unregisterMBean(objectName);
838 // else
839
// //just to unregister dotted name
840
// notifyUnregisterMBean(objectName, getConfigContext());
841
}
842                 catch (Throwable JavaDoc t)
843                 {
844                     //this is ok, some elements has no dotted name
845
_sLogger.fine("!!!!!!!!!!!!!! Can not unregister MBean: "+objectName);
846                 }
847             }
848         }
849    }
850     
851    //****************************************************************************************************
852
/* collects beans (own and all children) base on ConfigBeansXPathes
853     * and adds them to provided arrayList
854     *
855     * called recursively
856     * @param bean ConfigBean to investigate
857     * @param arr arraylist for accumulating of objectNames
858     *
859     */

860    private void collectChildrenObjectNames(ConfigBean bean, String JavaDoc domainName, ArrayList JavaDoc arr)
861    {
862         try
863         {
864             ConfigBean[] beans = bean.getAllChildBeans();
865             for(int i=0; i<beans.length; i++)
866             {
867                 collectChildrenObjectNames(beans[i], domainName, arr);
868             }
869         }
870         catch(Exception JavaDoc e)
871         {
872             //ignore exceptions (mabe there is no correspondent ObjectName
873
}
874         try
875         {
876             ObjectName JavaDoc name = getObjectNameForConfigBean(bean, domainName);
877             if(name!=null)
878             {
879                arr.add(name);
880                _sLogger.log(Level.FINEST, "******collectChildrenObjectNames.add-> ");
881             }
882         }
883         catch(MalformedObjectNameException JavaDoc e)
884         {
885             String JavaDoc xpath = bean.getAbsoluteXPath("");
886             _sLogger.log(Level.FINE, "Object name malformed for bean: "+ xpath, e);
887         }
888    }
889    
890    /* ****************************************************************************************************
891     * helper method - find MBeanNaminginfo for given ConfgBean
892     * @param bean - ConfigBean
893     * @param domainName - domainName using to form MBeanNameinInfo (first tag in location)
894     */

895    private MBeanNamingInfo getNamingInfoForConfigBean(ConfigBean bean, String JavaDoc domainName)
896     {
897         if(bean == null)
898             return null;
899         try
900         {
901             String JavaDoc xpath = bean.getAbsoluteXPath("");
902             MBeanRegistryEntry entry = findMBeanRegistryEntryByXPath(xpath);
903             MBeanNamingDescriptor descr = entry.getNamingDescriptor();
904             String JavaDoc [] parms = descr.extractParmListFromXPath(xpath);
905             if(parms!=null && parms.length>0 && parms[0]==null)
906                 parms[0] = domainName;
907             return new MBeanNamingInfo(descr, descr.getType(), parms);
908         }
909         catch (Exception JavaDoc e)
910         {
911             // it is ok. not all config beans have entries in registry
912
return null;
913         }
914    }
915    /* ****************************************************************************************************
916     * helper method - returns ObjectName correspondent to ConfigBean
917     * @param bean - ConfigBean to find ObjectName
918     * @param domainName - domainName using to form ObjectName
919     */

920    public ObjectName JavaDoc getObjectNameForConfigBean(ConfigBean bean, String JavaDoc domainName) throws MalformedObjectNameException JavaDoc
921     {
922         MBeanNamingInfo namingInfo = getNamingInfoForConfigBean(bean, domainName);
923         if(namingInfo!=null)
924             return namingInfo.getObjectName();
925         return null;
926    }
927    /**
928     * returns element name description
929     * like "custom resource myResource"
930     */

931    public String JavaDoc getConfigElementPrintName(String JavaDoc xpath, boolean bIncludingKey, boolean bReplaceRefByParentElem)
932    {
933        xpath = MBeanMetaHelper.cutAttributeTokenFromXPath(xpath.trim());
934        MBeanRegistryEntry entry = findMBeanRegistryEntryByXPath(xpath);
935        String JavaDoc printName;
936        String JavaDoc elemName = MBeanMetaHelper.extractLastElemNameFromXPath(xpath);
937        if(bReplaceRefByParentElem && elemName.endsWith("-ref"))
938        {
939           xpath = MBeanMetaHelper.cutLastElementFromXPath(xpath);
940           elemName = MBeanMetaHelper.extractLastElemNameFromXPath(xpath);
941        }
942        if(entry==null ||
943           (printName = entry.getElementPrintName())==null)
944        {
945            //generic name convertion to print name
946
printName = elemName.replace('-', ' ');
947        }
948        String JavaDoc key = MBeanMetaHelper.getMultipleElementKeyValue(xpath);
949        if(key!=null && bIncludingKey)
950            printName = printName + " '" + key + "'";
951        return printName;
952    }
953 }
954
Popular Tags