KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > modeler > Registry


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17
18 package org.apache.commons.modeler;
19
20
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.net.URL JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Hashtable JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31
32 import javax.management.DynamicMBean JavaDoc;
33 import javax.management.MBeanAttributeInfo JavaDoc;
34 import javax.management.MBeanInfo JavaDoc;
35 import javax.management.MBeanOperationInfo JavaDoc;
36 import javax.management.MBeanRegistration JavaDoc;
37 import javax.management.MBeanServer JavaDoc;
38 import javax.management.MBeanServerFactory JavaDoc;
39 import javax.management.MalformedObjectNameException JavaDoc;
40 import javax.management.ObjectName JavaDoc;
41 import javax.management.modelmbean.ModelMBean JavaDoc;
42
43 import org.apache.commons.logging.Log;
44 import org.apache.commons.logging.LogFactory;
45 import org.apache.commons.modeler.modules.ModelerSource;
46
47 /*
48    Issues:
49    - exceptions - too many "throws Exception"
50    - double check the interfaces
51    - start removing the use of the experimental methods in tomcat, then remove
52      the methods ( before 1.1 final )
53    - is the security enough to prevent Registry beeing used to avoid the permission
54     checks in the mbean server ?
55 */

56
57 /**
58  * Registry for modeler MBeans.
59  *
60  * This is the main entry point into modeler. It provides methods to create
61  * and manipulate model mbeans and simplify their use.
62  *
63  * Starting with version 1.1, this is no longer a singleton and the static
64  * methods are strongly deprecated. In a container environment we can expect
65  * different applications to use different registries.
66  *
67  * This class is itself an mbean.
68  *
69  * IMPORTANT: public methods not marked with @since x.x are experimental or
70  * internal. Should not be used.
71  *
72  * @author Craig R. McClanahan
73  * @author Costin Manolache
74  */

75 public class Registry implements RegistryMBean, MBeanRegistration JavaDoc {
76     /** Experimental support for manifest-based discovery.
77      */

78     public static String JavaDoc MODELER_MANIFEST="/META-INF/mbeans-descriptors.xml";
79
80     /**
81      * The Log instance to which we will write our log messages.
82      */

83     private static Log log = LogFactory.getLog(Registry.class);
84
85     // Support for the factory methods
86

87     /** Will be used to isolate different apps and enhance security
88      */

89     private static HashMap JavaDoc perLoaderRegistries=null;
90
91     /**
92      * The registry instance created by our factory method the first time
93      * it is called.
94      */

95     private static Registry registry = null;
96
97     // Per registy fields
98

99     /**
100      * The <code>MBeanServer</code> instance that we will use to register
101      * management beans.
102      */

103     private MBeanServer JavaDoc server = null;
104
105     /**
106      * The set of ManagedBean instances for the beans this registry
107      * knows about, keyed by name.
108      */

109     private HashMap JavaDoc descriptors = new HashMap JavaDoc();
110
111     /** List of managed byeans, keyed by class name
112      */

113     private HashMap JavaDoc descriptorsByClass = new HashMap JavaDoc();
114
115     // map to avoid duplicated searching or loading descriptors
116
private HashMap JavaDoc searchedPaths=new HashMap JavaDoc();
117     
118     private Object JavaDoc key;
119     private Object JavaDoc guard;
120
121     // Id - small ints to use array access. No reset on stop()
122
private Hashtable JavaDoc idDomains=new Hashtable JavaDoc();
123     private Hashtable JavaDoc ids=new Hashtable JavaDoc();
124
125     
126     // ----------------------------------------------------------- Constructors
127

128     /**
129      */

130      public Registry() {
131         super();
132     }
133
134     // -------------------- Static methods --------------------
135
// Factories
136

137     /**
138      * Factory method to create (if necessary) and return our
139      * <code>Registry</code> instance.
140      *
141      * Use this method to obtain a Registry - all other static methods
142      * are deprecated and shouldn't be used.
143      *
144      * The current version uses a static - future versions could use
145      * the thread class loader.
146      *
147      * @param key Support for application isolation. If null, the context class
148      * loader will be used ( if setUseContextClassLoader is called ) or the
149      * default registry is returned.
150      * @param guard Prevent access to the registry by untrusted components
151      *
152      * @since 1.1
153      */

154     public synchronized static Registry getRegistry(Object JavaDoc key, Object JavaDoc guard) {
155         Registry localRegistry;
156         if( perLoaderRegistries!=null ) {
157             if( key==null )
158                 key=Thread.currentThread().getContextClassLoader();
159             if( key != null ) {
160                 localRegistry=(Registry)perLoaderRegistries.get(key);
161                 if( localRegistry == null ) {
162                     localRegistry=new Registry();
163                     localRegistry.key=key;
164                     localRegistry.guard=guard;
165                     perLoaderRegistries.put( key, localRegistry );
166                     return localRegistry;
167                 }
168                 if( localRegistry.guard != null &&
169                         localRegistry.guard != guard ) {
170                     return null; // XXX Should I throw a permission ex ?
171
}
172                 return localRegistry;
173             }
174         }
175
176         // static
177
if (registry == null) {
178             registry = new Registry();
179         }
180         if( registry.guard != null &&
181                 registry.guard != guard ) {
182             return null;
183         }
184         return (registry);
185     }
186     
187     /** Allow containers to isolate apps. Can be called only once.
188      * It is highly recommended you call this method if using Registry in
189      * a container environment. The default is false for backward compatibility
190      *
191      * @param enable
192      * @since 1.1
193      */

194     public static void setUseContextClassLoader( boolean enable ) {
195         if( enable ) {
196             perLoaderRegistries=new HashMap JavaDoc();
197         }
198     }
199     
200     // -------------------- Generic methods --------------------
201

202     /** Set a guard object that will prevent access to this registry
203      * by unauthorized components
204      *
205      * @param guard
206      *
207      * @since 1.1
208      */

209     public void setGuard( Object JavaDoc guard ) {
210         if( this.guard!=null ) {
211             return; // already set, only once
212
}
213         this.guard=guard;
214     }
215
216     /** Lifecycle method - clean up the registry metadata.
217      *
218      * @since 1.1
219      */

220     public void stop() {
221         descriptorsByClass = new HashMap JavaDoc();
222         descriptors = new HashMap JavaDoc();
223         searchedPaths=new HashMap JavaDoc();
224     }
225     
226     /**
227      * Load an extended mlet file. The source can be an URL, File or
228      * InputStream.
229      *
230      * All mbeans will be instantiated, registered and the attributes will be
231      * set. The result is a list of ObjectNames.
232      *
233      * @param source InputStream or URL of the file
234      * @param cl ClassLoader to be used to load the mbeans, or null to use the
235      * default JMX mechanism ( i.e. all registered loaders )
236      * @return List of ObjectName for the loaded mbeans
237      * @throws Exception
238      *
239      * @since 1.1
240      */

241     public List JavaDoc loadMBeans( Object JavaDoc source, ClassLoader JavaDoc cl )
242             throws Exception JavaDoc
243     {
244         return load("MbeansSource", source, null );
245     }
246
247
248     /** Load descriptors. The source can be a File or URL or InputStream for the
249      * descriptors file. In the case of File and URL, if the extension is ".ser"
250      * a serialized version will be loaded.
251      *
252      * Also ( experimental for now ) a ClassLoader - in which case META-INF/ will
253      * be used.
254      *
255      * This method should be used to explicitely load metadata - but this is not
256      * required in most cases. The registerComponent() method will find metadata
257      * in the same pacakge.
258      *
259      * @param source
260      */

261     public void loadMetadata(Object JavaDoc source ) throws Exception JavaDoc {
262         if( source instanceof ClassLoader JavaDoc ) {
263             loadMetaInfDescriptors((ClassLoader JavaDoc)source);
264             return;
265         } else {
266             loadDescriptors( null, source, null );
267         }
268         
269     }
270
271     /** Register a bean by creating a modeler mbean and adding it to the
272      * MBeanServer.
273      *
274      * If metadata is not loaded, we'll look up and read a file named
275      * "mbeans-descriptors.ser" or "mbeans-descriptors.xml" in the same package
276      * or parent.
277      *
278      * If the bean is an instance of DynamicMBean. it's metadata will be converted
279      * to a model mbean and we'll wrap it - so modeler services will be supported
280      *
281      * If the metadata is still not found, introspection will be used to extract
282      * it automatically.
283      *
284      * If an mbean is already registered under this name, it'll be first
285      * unregistered.
286      *
287      * If the component implements MBeanRegistration, the methods will be called.
288      * If the method has a method "setRegistry" that takes a RegistryMBean as
289      * parameter, it'll be called with the current registry.
290      *
291      *
292      * @param bean Object to be registered
293      * @param oname Name used for registration
294      * @param type The type of the mbean, as declared in mbeans-descriptors. If
295      * null, the name of the class will be used. This can be used as a hint or
296      * by subclasses.
297      *
298      * @since 1.1
299      */

300     public void registerComponent(Object JavaDoc bean, String JavaDoc oname, String JavaDoc type)
301            throws Exception JavaDoc
302     {
303         registerComponent(bean, new ObjectName JavaDoc(oname), type);
304     }
305
306     /** Unregister a component. We'll first check if it is registered,
307      * and mask all errors. This is mostly a helper.
308      *
309      * @param oname
310      *
311      * @since 1.1
312      */

313     public void unregisterComponent( String JavaDoc oname ) {
314         try {
315             unregisterComponent(new ObjectName JavaDoc(oname));
316         } catch (MalformedObjectNameException JavaDoc e) {
317             log.info("Error creating object name " + e );
318         }
319     }
320     
321
322     /** Invoke a operation on a list of mbeans. Can be used to implement
323      * lifecycle operations.
324      *
325      * @param mbeans list of ObjectName on which we'll invoke the operations
326      * @param operation Name of the operation ( init, start, stop, etc)
327      * @param failFirst If false, exceptions will be ignored
328      * @throws Exception
329      * @since 1.1
330      */

331     public void invoke( List JavaDoc mbeans, String JavaDoc operation, boolean failFirst )
332             throws Exception JavaDoc
333     {
334         if( mbeans==null ) {
335             return;
336         }
337         Iterator JavaDoc itr=mbeans.iterator();
338         while(itr.hasNext()) {
339             Object JavaDoc current=itr.next();
340             ObjectName JavaDoc oN=null;
341             try {
342                 if( current instanceof ObjectName JavaDoc) {
343                     oN=(ObjectName JavaDoc)current;
344                 }
345                 if( current instanceof String JavaDoc ) {
346                     oN=new ObjectName JavaDoc( (String JavaDoc)current );
347                 }
348                 if( oN==null ) {
349                     continue;
350                 }
351                 if( getMethodInfo(oN, operation) == null) {
352                     continue;
353                 }
354                 getMBeanServer().invoke(oN, operation,
355                         new Object JavaDoc[] {}, new String JavaDoc[] {});
356
357             } catch( Exception JavaDoc t ) {
358                 if( failFirst ) throw t;
359                 log.info("Error initializing " + current + " " + t.toString());
360             }
361         }
362     }
363
364     // -------------------- ID registry --------------------
365

366     /** Return an int ID for faster access. Will be used for notifications
367      * and for other operations we want to optimize.
368      *
369      * @param domain Namespace
370      * @param name Type of the notification
371      * @return An unique id for the domain:name combination
372      * @since 1.1
373      */

374     public synchronized int getId( String JavaDoc domain, String JavaDoc name) {
375         if( domain==null) {
376             domain="";
377         }
378         Hashtable JavaDoc domainTable=(Hashtable JavaDoc)idDomains.get( domain );
379         if( domainTable == null ) {
380             domainTable=new Hashtable JavaDoc();
381             idDomains.put( domain, domainTable);
382         }
383         if( name==null ) {
384             name="";
385         }
386         Integer JavaDoc i=(Integer JavaDoc)domainTable.get(name);
387         
388         if( i!= null ) {
389             return i.intValue();
390         }
391
392         int id[]=(int [])ids.get( domain );
393         if( id == null ) {
394             id=new int[1];
395             ids.put( domain, id);
396         }
397         int code=id[0]++;
398         domainTable.put( name, new Integer JavaDoc( code ));
399         return code;
400     }
401     
402     // -------------------- Metadata --------------------
403
// methods from 1.0
404

405     /**
406      * Add a new bean metadata to the set of beans known to this registry.
407      * This is used by internal components.
408      *
409      * @param bean The managed bean to be added
410      * @since 1.0
411      */

412     public void addManagedBean(ManagedBean bean) {
413         // XXX Use group + name
414
descriptors.put(bean.getName(), bean);
415         if( bean.getType() != null ) {
416             descriptorsByClass.put( bean.getType(), bean );
417         }
418     }
419
420
421     /**
422      * Find and return the managed bean definition for the specified
423      * bean name, if any; otherwise return <code>null</code>.
424      *
425      * @param name Name of the managed bean to be returned. Since 1.1, both
426      * short names or the full name of the class can be used.
427      * @since 1.0
428      */

429     public ManagedBean findManagedBean(String JavaDoc name) {
430         // XXX Group ?? Use Group + Type
431
ManagedBean mb=((ManagedBean) descriptors.get(name));
432         if( mb==null )
433             mb=(ManagedBean)descriptorsByClass.get(name);
434         return mb;
435     }
436     
437     /**
438      * Return the set of bean names for all managed beans known to
439      * this registry.
440      *
441      * @since 1.0
442      */

443     public String JavaDoc[] findManagedBeans() {
444         return ((String JavaDoc[]) descriptors.keySet().toArray(new String JavaDoc[0]));
445     }
446
447
448     /**
449      * Return the set of bean names for all managed beans known to
450      * this registry that belong to the specified group.
451      *
452      * @param group Name of the group of interest, or <code>null</code>
453      * to select beans that do <em>not</em> belong to a group
454      * @since 1.0
455      */

456     public String JavaDoc[] findManagedBeans(String JavaDoc group) {
457
458         ArrayList JavaDoc results = new ArrayList JavaDoc();
459         Iterator JavaDoc items = descriptors.values().iterator();
460         while (items.hasNext()) {
461             ManagedBean item = (ManagedBean) items.next();
462             if ((group == null) && (item.getGroup() == null)) {
463                 results.add(item.getName());
464             } else if (group.equals(item.getGroup())) {
465                 results.add(item.getName());
466             }
467         }
468         String JavaDoc values[] = new String JavaDoc[results.size()];
469         return ((String JavaDoc[]) results.toArray(values));
470
471     }
472
473
474     /**
475      * Remove an existing bean from the set of beans known to this registry.
476      *
477      * @param bean The managed bean to be removed
478      * @since 1.0
479      */

480     public void removeManagedBean(ManagedBean bean) {
481        // TODO: change this to use group/name
482
descriptors.remove(bean.getName());
483         descriptorsByClass.remove( bean.getType());
484     }
485
486     // -------------------- Deprecated 1.0 methods --------------------
487

488     /**
489      * Factory method to create (if necessary) and return our
490      * <code>MBeanServer</code> instance.
491      *
492      * @since 1.0
493      * @deprecated Use the instance method
494      */

495     public static MBeanServer JavaDoc getServer() {
496         return Registry.getRegistry().getMBeanServer();
497     }
498
499     /**
500      * Set the <code>MBeanServer</code> to be utilized for our
501      * registered management beans.
502      *
503      * @param mbeanServer The new <code>MBeanServer</code> instance
504      * @since 1.0
505      * @deprecated Use the instance method
506      */

507     public static void setServer(MBeanServer JavaDoc mbeanServer) {
508         Registry.getRegistry().setServer(mbeanServer);
509     }
510
511     /**
512      * Load the registry from the XML input found in the specified input
513      * stream.
514      *
515      * @param stream InputStream containing the registry configuration
516      * information
517      *
518      * @exception Exception if any parsing or processing error occurs
519      * @deprecated use normal class method instead
520      * @since 1.0
521      */

522     public static void loadRegistry(InputStream JavaDoc stream) throws Exception JavaDoc {
523         Registry registry = getRegistry();
524         registry.loadMetadata(stream);
525     }
526
527     /** Get a "singelton" registry, or one per thread if setUseContextLoader
528      * was called
529      *
530      * @deprecated Not enough info - use the method that takes CL and domain
531      * @since 1.0
532      */

533     public synchronized static Registry getRegistry() {
534         return getRegistry(null, null);
535     }
536
537     // -------------------- Helpers --------------------
538

539     /** Get the type of an attribute of the object, from the metadata.
540      *
541      * @param oname
542      * @param attName
543      * @return null if metadata about the attribute is not found
544      * @since 1.1
545      */

546     public String JavaDoc getType( ObjectName JavaDoc oname, String JavaDoc attName )
547     {
548         String JavaDoc type=null;
549         MBeanInfo JavaDoc info=null;
550         try {
551             info=server.getMBeanInfo(oname);
552         } catch (Exception JavaDoc e) {
553             log.info( "Can't find metadata for object" + oname );
554             return null;
555         }
556
557         MBeanAttributeInfo JavaDoc attInfo[]=info.getAttributes();
558         for( int i=0; i<attInfo.length; i++ ) {
559             if( attName.equals(attInfo[i].getName())) {
560                 type=attInfo[i].getType();
561                 return type;
562             }
563         }
564         return null;
565     }
566
567     /** Find the operation info for a method
568      *
569      * @param oname
570      * @param opName
571      * @return the operation info for the specified operation
572      */

573     public MBeanOperationInfo JavaDoc getMethodInfo( ObjectName JavaDoc oname, String JavaDoc opName )
574     {
575         String JavaDoc type=null;
576         MBeanInfo JavaDoc info=null;
577         try {
578             info=server.getMBeanInfo(oname);
579         } catch (Exception JavaDoc e) {
580             log.info( "Can't find metadata " + oname );
581             return null;
582         }
583         MBeanOperationInfo JavaDoc attInfo[]=info.getOperations();
584         for( int i=0; i<attInfo.length; i++ ) {
585             if( opName.equals(attInfo[i].getName())) {
586                 return attInfo[i];
587             }
588         }
589         return null;
590     }
591
592     /** Unregister a component. This is just a helper that
593      * avoids exceptions by checking if the mbean is already registered
594      *
595      * @param oname
596      */

597     public void unregisterComponent( ObjectName JavaDoc oname ) {
598         try {
599             if( getMBeanServer().isRegistered(oname)) {
600                 getMBeanServer().unregisterMBean(oname);
601             }
602         } catch( Throwable JavaDoc t ) {
603             log.error( "Error unregistering mbean ", t);
604         }
605     }
606
607     /**
608      * Factory method to create (if necessary) and return our
609      * <code>MBeanServer</code> instance.
610      *
611      */

612     public synchronized MBeanServer JavaDoc getMBeanServer() {
613         long t1=System.currentTimeMillis();
614
615         if (server == null) {
616             if( MBeanServerFactory.findMBeanServer(null).size() > 0 ) {
617                 server=(MBeanServer JavaDoc)MBeanServerFactory.findMBeanServer(null).get(0);
618                 if( log.isDebugEnabled() ) {
619                     log.debug("Using existing MBeanServer " + (System.currentTimeMillis() - t1 ));
620                 }
621             } else {
622                 server=MBeanServerFactory.createMBeanServer();
623                 if( log.isDebugEnabled() ) {
624                     log.debug("Creating MBeanServer"+ (System.currentTimeMillis() - t1 ));
625                 }
626             }
627         }
628         return (server);
629     }
630
631     /** Find or load metadata.
632      */

633     public ManagedBean findManagedBean(Object JavaDoc bean, Class JavaDoc beanClass, String JavaDoc type)
634         throws Exception JavaDoc
635     {
636         if( bean!=null && beanClass==null ) {
637             beanClass=bean.getClass();
638         }
639         
640         if( type==null ) {
641             type=beanClass.getName();
642         }
643         
644         // first look for existing descriptor
645
ManagedBean managed = findManagedBean(type);
646
647         // Search for a descriptor in the same package
648
if( managed==null ) {
649             // check package and parent packages
650
if( log.isDebugEnabled() ) {
651                 log.debug( "Looking for descriptor ");
652             }
653             findDescriptor( beanClass, type );
654
655             managed=findManagedBean(type);
656         }
657         
658         if( bean instanceof DynamicMBean JavaDoc ) {
659             if( log.isDebugEnabled() ) {
660                 log.debug( "Dynamic mbean support ");
661             }
662             // Dynamic mbean
663
loadDescriptors("MbeansDescriptorsDynamicMBeanSource",
664                     bean, type);
665
666             managed=findManagedBean(type);
667         }
668
669         // Still not found - use introspection
670
if( managed==null ) {
671             if( log.isDebugEnabled() ) {
672                 log.debug( "Introspecting ");
673             }
674
675             // introspection
676
loadDescriptors("MbeansDescriptorsIntrospectionSource",
677                     beanClass, type);
678
679             managed=findManagedBean(type);
680             if( managed==null ) {
681                 log.warn( "No metadata found for " + type );
682                 return null;
683             }
684             managed.setName( type );
685             addManagedBean(managed);
686         }
687         return managed;
688     }
689     
690
691     /** EXPERIMENTAL Convert a string to object, based on type. Used by several
692      * components. We could provide some pluggability. It is here to keep
693      * things consistent and avoid duplication in other tasks
694      *
695      * @param type Fully qualified class name of the resulting value
696      * @param value String value to be converted
697      * @return Converted value
698      */

699     public Object JavaDoc convertValue(String JavaDoc type, String JavaDoc value)
700     {
701         Object JavaDoc objValue=value;
702         
703         if( type==null || "java.lang.String".equals( type )) {
704             // string is default
705
objValue=value;
706         } else if( "javax.management.ObjectName".equals( type ) ||
707                 "ObjectName".equals( type )) {
708             try {
709                 objValue=new ObjectName JavaDoc( value );
710             } catch (MalformedObjectNameException JavaDoc e) {
711                 return null;
712             }
713         } else if( "java.lang.Integer".equals( type ) ||
714                 "int".equals( type )) {
715             objValue=new Integer JavaDoc( value );
716         } else if( "java.lang.Boolean".equals( type ) ||
717                 "boolean".equals( type )) {
718             objValue=new Boolean JavaDoc( value );
719         }
720         return objValue;
721     }
722     
723     /** Experimental.
724      *
725      * @param sourceType
726      * @param source
727      * @param param
728      * @return List of descriptors
729      * @throws Exception
730      * @deprecated bad interface, mixing of metadata and mbeans
731      */

732     public List JavaDoc load( String JavaDoc sourceType, Object JavaDoc source, String JavaDoc param)
733         throws Exception JavaDoc
734     {
735         if( log.isTraceEnabled()) {
736             log.trace("load " + source );
737         }
738         String JavaDoc location=null;
739         String JavaDoc type=null;
740         Object JavaDoc inputsource=null;
741
742         if( source instanceof DynamicMBean JavaDoc ) {
743             sourceType="MbeansDescriptorsDynamicMBeanSource";
744             inputsource=source;
745         } else if( source instanceof URL JavaDoc ) {
746             URL JavaDoc url=(URL JavaDoc)source;
747             location=url.toString();
748             type=param;
749             inputsource=url.openStream();
750             if( sourceType == null ) {
751                 sourceType = sourceTypeFromExt(location);
752             }
753         } else if( source instanceof File JavaDoc ) {
754             location=((File JavaDoc)source).getAbsolutePath();
755             inputsource=new FileInputStream JavaDoc((File JavaDoc)source);
756             type=param;
757             if( sourceType == null ) {
758                 sourceType = sourceTypeFromExt(location);
759             }
760         } else if( source instanceof InputStream JavaDoc ) {
761             type=param;
762             inputsource=source;
763         } else if( source instanceof Class JavaDoc ) {
764             location=((Class JavaDoc)source).getName();
765             type=param;
766             inputsource=source;
767             if( sourceType== null ) {
768                 sourceType="MbeansDescriptorsIntrospectionSource";
769             }
770         }
771         
772         if( sourceType==null ) {
773             sourceType="MbeansDescriptorsDOMSource";
774         }
775         ModelerSource ds=getModelerSource(sourceType);
776         List JavaDoc mbeans=ds.loadDescriptors(this, location, type, inputsource);
777
778         return mbeans;
779     }
780
781     private String JavaDoc sourceTypeFromExt( String JavaDoc s ) {
782         if( s.endsWith( ".ser")) {
783             return "MbeansDescriptorsSerSource";
784         }
785         else if( s.endsWith(".xml")) {
786             return "MbeansDescriptorsDOMSource";
787         }
788         return null;
789     }
790
791     /** Register a component
792      * XXX make it private
793      *
794      * @param bean
795      * @param oname
796      * @param type
797      * @throws Exception
798      */

799     public void registerComponent(Object JavaDoc bean, ObjectName JavaDoc oname, String JavaDoc type)
800            throws Exception JavaDoc
801     {
802         if( log.isDebugEnabled() ) {
803             log.debug( "Managed= "+ oname);
804         }
805
806         if( bean ==null ) {
807             log.error("Null component " + oname );
808             return;
809         }
810
811         try {
812             if( type==null ) {
813                 type=bean.getClass().getName();
814             }
815
816             ManagedBean managed = findManagedBean(bean.getClass(), type);
817
818             // The real mbean is created and registered
819
ModelMBean JavaDoc mbean = managed.createMBean(bean);
820
821             if( getMBeanServer().isRegistered( oname )) {
822                 if( log.isDebugEnabled()) {
823                     log.debug("Unregistering existing component " + oname );
824                 }
825                 getMBeanServer().unregisterMBean( oname );
826             }
827
828             getMBeanServer().registerMBean( mbean, oname);
829         } catch( Exception JavaDoc ex) {
830             log.error("Error registering " + oname, ex );
831             throw ex;
832         }
833     }
834
835     /** Lookup the component descriptor in the package and
836      * in the parent packages.
837      *
838      * @param packageName
839      */

840     public void loadDescriptors( String JavaDoc packageName, ClassLoader JavaDoc classLoader ) {
841         String JavaDoc res=packageName.replace( '.', '/');
842
843         if( log.isTraceEnabled() ) {
844             log.trace("Finding descriptor " + res );
845         }
846
847         if( searchedPaths.get( packageName ) != null ) {
848             return;
849         }
850         String JavaDoc descriptors=res + "/mbeans-descriptors.ser";
851
852         URL JavaDoc dURL=classLoader.getResource( descriptors );
853
854         if( dURL == null ) {
855             descriptors=res + "/mbeans-descriptors.xml";
856             dURL=classLoader.getResource( descriptors );
857         }
858         if( dURL == null ) {
859             return;
860         }
861
862         log.debug( "Found " + dURL);
863         searchedPaths.put( packageName, dURL );
864         try {
865             if( descriptors.endsWith(".xml" ))
866                 loadDescriptors("MbeansDescriptorsDOMSource", dURL, null);
867             else
868                 loadDescriptors("MbeansDescriptorsSerSource", dURL, null);
869             return;
870         } catch(Exception JavaDoc ex ) {
871             log.error("Error loading " + dURL);
872         }
873
874         return;
875     }
876
877     /** Experimental. Will become private, some code may still use it
878      *
879      * @param sourceType
880      * @param source
881      * @param param
882      * @throws Exception
883      * @deprecated
884      */

885     public void loadDescriptors( String JavaDoc sourceType, Object JavaDoc source, String JavaDoc param)
886         throws Exception JavaDoc
887     {
888         List JavaDoc mbeans=load( sourceType, source, param );
889         if( mbeans == null) return;
890
891         Iterator JavaDoc itr=mbeans.iterator();
892         while( itr.hasNext() ) {
893             Object JavaDoc mb=itr.next();
894             if( mb instanceof ManagedBean) {
895                 addManagedBean((ManagedBean)mb);
896             }
897         }
898     }
899
900     /** Discover all META-INF/modeler.xml files in classpath and register
901      * the components
902      *
903      * @since EXPERIMENTAL
904      */

905     private void loadMetaInfDescriptors(ClassLoader JavaDoc cl) {
906         try {
907             Enumeration JavaDoc en=cl.getResources(MODELER_MANIFEST);
908             while( en.hasMoreElements() ) {
909                 URL JavaDoc url=(URL JavaDoc)en.nextElement();
910                 InputStream JavaDoc is=url.openStream();
911                 if( log.isDebugEnabled()) log.debug("Loading " + url);
912                 loadDescriptors("MBeansDescriptorDOMSource", is, null );
913             }
914         } catch( Exception JavaDoc ex ) {
915             ex.printStackTrace();
916         }
917     }
918
919     /** Lookup the component descriptor in the package and
920      * in the parent packages.
921      *
922      * @param beanClass
923      * @param type
924      */

925     private void findDescriptor( Class JavaDoc beanClass, String JavaDoc type ) {
926         if( type==null ) {
927             type=beanClass.getName();
928         }
929         ClassLoader JavaDoc classLoader=null;
930         if( beanClass!=null ) {
931             classLoader=beanClass.getClassLoader();
932         }
933         if( classLoader==null ) {
934             classLoader=Thread.currentThread().getContextClassLoader();
935         }
936         if( classLoader==null ) {
937             classLoader=this.getClass().getClassLoader();
938         }
939         
940         String JavaDoc className=type;
941         String JavaDoc pkg=className;
942         while( pkg.indexOf( ".") > 0 ) {
943             int lastComp=pkg.lastIndexOf( ".");
944             if( lastComp <= 0 ) return;
945             pkg=pkg.substring(0, lastComp);
946             if( searchedPaths.get( pkg ) != null ) {
947                 return;
948             }
949             loadDescriptors(pkg, classLoader);
950         }
951         return;
952     }
953
954     private ModelerSource getModelerSource( String JavaDoc type )
955             throws Exception JavaDoc
956     {
957         if( type==null ) type="MbeansDescriptorsDOMSource";
958         if( type.indexOf( ".") < 0 ) {
959             type="org.apache.commons.modeler.modules." + type;
960         }
961
962         Class JavaDoc c=Class.forName( type );
963         ModelerSource ds=(ModelerSource)c.newInstance();
964         return ds;
965     }
966
967
968     // -------------------- Registration --------------------
969

970     public ObjectName JavaDoc preRegister(MBeanServer JavaDoc server,
971                                   ObjectName JavaDoc name) throws Exception JavaDoc
972     {
973         this.server=server;
974         return name;
975     }
976
977     public void postRegister(Boolean JavaDoc registrationDone) {
978     }
979
980     public void preDeregister() throws Exception JavaDoc {
981     }
982
983     public void postDeregister() {
984     }
985
986     
987     
988     
989     // -------------------- DEPRECATED METHODS --------------------
990
// May still be used in tomcat
991
// Never part of an official release
992

993     /** Called by a registry or by the container to unload a loader
994      * @param loader
995      */

996     public void unregisterRegistry(ClassLoader JavaDoc loader ) {
997         // XXX Cleanup ?
998
perLoaderRegistries.remove(loader);
999     }
1000
1001    public ManagedBean findManagedBean(Class JavaDoc beanClass, String JavaDoc type)
1002        throws Exception JavaDoc
1003    {
1004        return findManagedBean(null, beanClass, type);
1005    }
1006    
1007    /**
1008     * Set the <code>MBeanServer</code> to be utilized for our
1009     * registered management beans.
1010     *
1011     * @param server The new <code>MBeanServer</code> instance
1012     */

1013    public void setMBeanServer( MBeanServer JavaDoc server ) {
1014        this.server=server;
1015    }
1016
1017    public void resetMetadata() {
1018        stop();
1019    }
1020    /**
1021     * Load the registry from the XML input found in the specified input
1022     * stream.
1023     *
1024     * @param source Source to be used to load. Can be an InputStream or URL.
1025     *
1026     * @exception Exception if any parsing or processing error occurs
1027     */

1028    public void loadDescriptors( Object JavaDoc source )
1029            throws Exception JavaDoc
1030    {
1031        loadDescriptors("MbeansDescriptorsDOMSource", source, null );
1032    }
1033
1034    /** @deprecated - may still be used in code using pre-1.1 builds
1035     */

1036    public void registerComponent(Object JavaDoc bean, String JavaDoc domain, String JavaDoc type,
1037                                  String JavaDoc name)
1038            throws Exception JavaDoc
1039    {
1040        StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
1041        sb.append( domain ).append(":");
1042        sb.append( name );
1043        String JavaDoc nameStr=sb.toString();
1044        ObjectName JavaDoc oname=new ObjectName JavaDoc( nameStr );
1045        registerComponent(bean, oname, type );
1046    }
1047
1048    
1049
1050    // should be removed
1051
public void unregisterComponent( String JavaDoc domain, String JavaDoc name ) {
1052        try {
1053            ObjectName JavaDoc oname=new ObjectName JavaDoc( domain + ":" + name );
1054
1055            // XXX remove from our tables.
1056
getMBeanServer().unregisterMBean( oname );
1057        } catch( Throwable JavaDoc t ) {
1058            log.error( "Error unregistering mbean ", t );
1059        }
1060    }
1061    
1062    public List JavaDoc loadMBeans( Object JavaDoc source )
1063            throws Exception JavaDoc
1064    {
1065        return loadMBeans( source, null );
1066    }
1067
1068
1069    /**
1070     * Load the registry from a cached .ser file. This is typically 2-3 times
1071     * faster than parsing the XML.
1072     *
1073     * @param source Source to be used to load. Can be an InputStream or URL.
1074     *
1075     * @exception Exception if any parsing or processing error occurs
1076     * @deprecated Loaded automatically or using a File or Url ending in .ser
1077     */

1078    public void loadCachedDescriptors( Object JavaDoc source )
1079            throws Exception JavaDoc
1080    {
1081        loadDescriptors("MbeansDescriptorsSerSource", source, null );
1082    }
1083}
1084
Popular Tags