KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > appserv > management > util > jmx > JMXUtil


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 package com.sun.appserv.management.util.jmx;
24
25 import java.io.IOException JavaDoc;
26 import java.io.Serializable JavaDoc;
27
28 import java.util.Set JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.HashSet JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.ArrayList JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Arrays JavaDoc;
38 import java.util.regex.Pattern JavaDoc;
39 import java.util.Hashtable JavaDoc;
40
41 import java.lang.reflect.Method JavaDoc;
42
43 import javax.management.*;
44
45 import com.sun.appserv.management.util.stringifier.ArrayStringifier;
46 import com.sun.appserv.management.util.misc.ArrayUtil;
47 import com.sun.appserv.management.util.misc.GSetUtil;
48 import com.sun.appserv.management.util.misc.MapUtil;
49 import com.sun.appserv.management.util.misc.TypeCast;
50 import com.sun.appserv.management.util.misc.RegexUtil;
51
52 import com.sun.appserv.management.util.jmx.stringifier.MBeanOperationInfoStringifier;
53 import com.sun.appserv.management.util.jmx.stringifier.MBeanFeatureInfoStringifierOptions;
54 import com.sun.appserv.management.util.jmx.stringifier.MBeanAttributeInfoStringifier;
55 import com.sun.appserv.management.util.jmx.stringifier.ObjectNameStringifier;
56 import com.sun.appserv.management.util.misc.ArrayConversion;
57
58 import com.sun.appserv.management.util.stringifier.SmartStringifier;
59
60
61
62 /**
63  */

64 public final class JMXUtil
65 {
66     
67     public final static String JavaDoc MBEAN_SERVER_DELEGATE =
68                             "JMImplementation:type=MBeanServerDelegate";
69     
70     public final static String JavaDoc MBEAN_SERVER_ID_ATTRIBUTE_NAME =
71                             "MBeanServerId";
72                             
73     /**
74         The wilcard property at the end of an ObjectName which indicates
75         that it's an ObjectName pattern.
76      */

77     public final static String JavaDoc WILD_PROP = ",*";
78     
79     /**
80         The wilcard property at the end of an ObjectName which indicates
81         that all properties should be matched.
82      */

83     public final static String JavaDoc WILD_ALL = "*";
84     
85     
86         public static ObjectName
87     getMBeanServerDelegateObjectName()
88     {
89         return( newObjectName( "JMImplementation:type=MBeanServerDelegate" ) );
90     }
91     
92         public static void
93     listenToMBeanServerDelegate(
94         final MBeanServerConnection conn,
95         final NotificationListener listener,
96         final NotificationFilter filter,
97         final Object JavaDoc handback)
98         throws IOException JavaDoc, InstanceNotFoundException
99     {
100         conn.addNotificationListener(
101             getMBeanServerDelegateObjectName(), listener, filter, handback );
102     }
103     
104         public static String JavaDoc
105     getMBeanServerID( final MBeanServerConnection conn )
106         throws IOException JavaDoc,
107         ReflectionException, InstanceNotFoundException, AttributeNotFoundException,
108         MBeanException
109     {
110         return( (String JavaDoc)conn.getAttribute( getMBeanServerDelegateObjectName(),
111                     MBEAN_SERVER_ID_ATTRIBUTE_NAME ) );
112     }
113     
114     
115     /**
116         Create a new ObjectName, caller is guaranteeing that the name is
117         well-formed (a RuntimeException will be thrown if not). This avoids
118         having to catch all sorts of JMX exceptions.
119         <p>
120         <b>Do not call this method if there is not 100% certainty of a well-formed name.</b>
121      */

122         public static ObjectName
123     newObjectName( final String JavaDoc name )
124     {
125         try
126         {
127             return( new ObjectName( name ) );
128         }
129         catch( Exception JavaDoc e )
130         {
131             throw new RuntimeException JavaDoc( e.getMessage(), e );
132         }
133     }
134     
135         public static ObjectName
136     newObjectName(
137         final ObjectName objectName,
138         final String JavaDoc props )
139     {
140         final String JavaDoc domain = objectName.getDomain();
141         final String JavaDoc existingProps = objectName.getKeyPropertyListString();
142         final String JavaDoc allProps = concatenateProps( existingProps, props );
143         return( newObjectName( domain, allProps ) );
144     }
145     
146         public static ObjectName
147     newObjectName(
148         final String JavaDoc domain,
149         final String JavaDoc props )
150     {
151         return( newObjectName( domain + ":" + props ) );
152     }
153     
154     /**
155         Build an ObjectName pattern.
156         
157         @param domain the JMX domain
158         @param props properties of the ObjectName
159      */

160         public static ObjectName
161     newObjectNamePattern(
162         final String JavaDoc domain,
163         final String JavaDoc props )
164     {
165         String JavaDoc actualProps = null;
166         
167         if ( props.endsWith( JMXUtil.WILD_PROP ) ||
168             props.equals( JMXUtil.WILD_ALL ) )
169         {
170             actualProps = props;
171         }
172         else if ( props.length() == 0 )
173         {
174             actualProps = "*";
175         }
176         else
177         {
178             actualProps = props + WILD_PROP;
179         }
180         
181         return( newObjectName( domain + ":" + actualProps ) );
182     }
183     
184     
185     /**
186         Build an ObjectName pattern.
187         
188         @param domain the JMX domain
189         @param props properties of the ObjectName
190      */

191         public static ObjectName
192     newObjectNamePattern(
193         final String JavaDoc domain,
194         final Map JavaDoc<String JavaDoc,String JavaDoc> props )
195     {
196         final String JavaDoc propsString = mapToProps( props );
197         
198         return( JMXUtil.newObjectNamePattern( domain, propsString ) );
199     }
200     
201         public static String JavaDoc
202     mapToProps( final Map JavaDoc<String JavaDoc,String JavaDoc> propsMap )
203     {
204         return( MapUtil.toString( propsMap, "," ) );
205     }
206     
207         public static ObjectName
208     removeProperty(
209         final ObjectName objectName,
210         final String JavaDoc key )
211     {
212         ObjectName nameWithoutKey = objectName;
213         
214         if ( objectName.getKeyProperty( key ) != null )
215         {
216             final String JavaDoc domain = objectName.getDomain();
217             final Hashtable JavaDoc<String JavaDoc,String JavaDoc> props =
218                 TypeCast.asHashtable( objectName.getKeyPropertyList() );
219             
220             props.remove( key );
221             
222             if ( objectName.isPropertyPattern() )
223             {
224                 final String JavaDoc propsString = mapToProps( props );
225             
226                 nameWithoutKey = newObjectNamePattern( domain,
227                         nameWithoutKey.getKeyPropertyListString() );
228             }
229             else
230             {
231                 try
232                 {
233                     nameWithoutKey = new ObjectName( domain, props );
234                 }
235                 catch( Exception JavaDoc e )
236                 {
237                     throw new RuntimeException JavaDoc( e );
238                 }
239             }
240         }
241         
242         return( nameWithoutKey );
243     }
244     
245     
246         private
247     JMXUtil()
248     {
249         // disallow;
250
}
251     
252     public static final String JavaDoc GET = "get";
253     public static final String JavaDoc SET = "set";
254     public static final String JavaDoc IS = "is";
255     
256         public static String JavaDoc
257     makeProp( String JavaDoc name, String JavaDoc value )
258     {
259         return( name + "=" + value );
260     }
261     
262         public static String JavaDoc
263     concatenateProps( String JavaDoc props1, String JavaDoc props2 )
264     {
265         String JavaDoc result = null;
266         
267         if ( props1.length() == 0 )
268         {
269             result = props2;
270         }
271         else if ( props2.length() == 0 )
272         {
273             result = props1;
274         }
275         else
276         {
277             result = props1 + "," + props2;
278         }
279         
280         return( result );
281     }
282     
283         public static String JavaDoc
284     concatenateProps( String JavaDoc props1, String JavaDoc props2, String JavaDoc props3 )
285     {
286         return( concatenateProps( concatenateProps( props1, props2), props3) );
287     }
288     
289     
290     
291     /**
292         Convert a Set of ObjectName into an array
293         
294         @param objectNameSet a Set of ObjectName
295         @return an ObjectName[]
296      */

297         public static ObjectName[]
298     objectNameSetToArray( final Set JavaDoc<ObjectName> objectNameSet )
299     {
300         final ObjectName[] objectNames = new ObjectName[ objectNameSet.size() ];
301         objectNameSet.toArray( objectNames );
302         
303         return( objectNames );
304     }
305     
306     
307     /**
308         @param key the property name, within the ObjectName
309         @param objectNames
310         @return values from each ObjectName
311      */

312         public static String JavaDoc[]
313     getKeyProperty( String JavaDoc key, ObjectName[] objectNames )
314     {
315         final String JavaDoc[] values = new String JavaDoc[ objectNames.length ];
316         
317         for( int i = 0; i < objectNames.length; ++i )
318         {
319             values[ i ] = objectNames[ i ].getKeyProperty( key );
320         }
321         
322         return( values );
323     }
324     
325     /**
326         @param objectName
327         @param key
328         @return an ObjectName property with the specified key
329      */

330         public static String JavaDoc
331     getProp(
332         final ObjectName objectName,
333         final String JavaDoc key )
334     {
335         final String JavaDoc value = objectName.getKeyProperty( key );
336         if ( value == null )
337         {
338             return( null );
339         }
340         
341         return( makeProp( key, value ) );
342     }
343     
344         public static String JavaDoc
345     getProps(
346         final ObjectName objectName,
347         final Set JavaDoc<String JavaDoc> propKeys )
348     {
349         return( getProps( objectName, propKeys, false ) );
350     }
351
352         public static String JavaDoc
353     getProps(
354         final ObjectName objectName,
355         final Set JavaDoc<String JavaDoc> propKeys,
356         final boolean ignoreMissing )
357     {
358         String JavaDoc props = "";
359         
360         final Iterator JavaDoc iter = propKeys.iterator();
361         while( iter.hasNext() )
362         {
363             final String JavaDoc key = (String JavaDoc)iter.next();
364             
365             final String JavaDoc pair = getProp( objectName, key );
366             if ( pair != null )
367             {
368                 props = concatenateProps( props, pair );
369             }
370             else if ( ! ignoreMissing )
371             {
372                 throw new IllegalArgumentException JavaDoc(
373                     "key not found: " + key + " in " + objectName );
374             }
375         }
376         return( props );
377     }
378     
379     /**
380         @param key the property name, within the ObjectName
381         @param objectNameSet
382         @return values from each ObjectName
383      */

384         public static String JavaDoc[]
385     getKeyProperty( String JavaDoc key, Set JavaDoc<ObjectName> objectNameSet )
386     {
387         final ObjectName[] objectNames =
388             JMXUtil.objectNameSetToArray( objectNameSet );
389         
390         return( getKeyProperty( key, objectNames ) );
391     }
392     
393
394     /**
395         @param key the property name, within the ObjectName
396         @param objectNameSet
397         @return values from each ObjectName
398      */

399         public static Set JavaDoc<String JavaDoc>
400     getKeyPropertySet( String JavaDoc key, Set JavaDoc<ObjectName> objectNameSet )
401     {
402         final ObjectName[] objectNames =
403             JMXUtil.objectNameSetToArray( objectNameSet );
404         
405         final String JavaDoc[] values = getKeyProperty( key, objectNames );
406         
407         return( ArrayConversion.arrayToSet( values ) );
408     }
409     
410     /**
411         Find the first key that is present in the ObjectName
412         
413         @param candidateKeys
414         @param objectName
415         @return first key present in the ObjectName
416      */

417         public static String JavaDoc
418     findKey(
419         final Set JavaDoc<String JavaDoc> candidateKeys,
420         final ObjectName objectName )
421     {
422         final Iterator JavaDoc iter = candidateKeys.iterator();
423         
424         String JavaDoc match = null;
425         
426         while ( iter.hasNext() )
427         {
428             final String JavaDoc key = (String JavaDoc)iter.next();
429             
430             if ( objectName.getKeyProperty( key ) != null )
431             {
432                 match = key;
433                 break;
434             }
435         }
436         
437         return( match );
438     }
439     
440     
441     /**
442         Find all ObjectName(s) that contains the associated key and value
443         
444         @param objectNames
445         @param propertyKey
446         @param propertyValue
447         @return Set of all ObjectName that match
448      */

449         public static Set JavaDoc<ObjectName>
450     findByProperty(
451         final Set JavaDoc<ObjectName> objectNames,
452         final String JavaDoc propertyKey,
453         final String JavaDoc propertyValue )
454     {
455         final Set JavaDoc<ObjectName> result = new HashSet JavaDoc<ObjectName>();
456         
457         final Iterator JavaDoc iter = objectNames.iterator();
458         while ( iter.hasNext() )
459         {
460             final ObjectName objectName = (ObjectName)iter.next();
461             
462             final String JavaDoc value = objectName.getKeyProperty( propertyKey );
463             if ( propertyValue.equals( value ) )
464             {
465                 result.add( objectName );
466             }
467         }
468         
469         return( result );
470     }
471     
472     /**
473         Change or add a key property in an ObjectName.
474      */

475         public static ObjectName
476     setKeyProperty( final ObjectName objectName, final String JavaDoc key, final String JavaDoc value )
477     {
478         final String JavaDoc domain = objectName.getDomain();
479         final Hashtable JavaDoc<String JavaDoc,String JavaDoc> props = TypeCast.asHashtable( objectName.getKeyPropertyList() );
480         
481         props.put( key, value );
482         
483         ObjectName newObjectName = null;
484         try
485         {
486             newObjectName = new ObjectName( domain, props );
487         }
488         catch( MalformedObjectNameException e )
489         {
490             throw new RuntimeException JavaDoc( e );
491         }
492         
493         return( newObjectName );
494     }
495     
496         private static String JavaDoc
497     toString( Object JavaDoc o )
498     {
499         return( SmartStringifier.toString( o ) );
500     }
501     
502         public static void
503     unregisterAll( final MBeanServerConnection conn, final Set JavaDoc<ObjectName> allNames)
504         throws IOException JavaDoc, MalformedObjectNameException, MBeanRegistrationException
505     {
506         for( final ObjectName name : allNames )
507         {
508             try
509             {
510                 conn.unregisterMBean( name );
511             }
512             catch( Exception JavaDoc e )
513             {
514                 // OK, gone, it objects, etc
515
}
516         }
517     }
518     
519         public static void
520     unregisterAll( final MBeanServerConnection conn )
521         throws IOException JavaDoc, MalformedObjectNameException, MBeanRegistrationException
522     {
523         unregisterAll( conn, queryNames( conn, new ObjectName( "*:*" ), null ) );
524     }
525     
526         public static String JavaDoc[]
527     getAllAttributeNames(
528         final MBeanServerConnection conn,
529         final ObjectName objectName )
530         throws IOException JavaDoc,
531             ReflectionException, IntrospectionException, InstanceNotFoundException
532     {
533         return( getAttributeNames( getAttributeInfos( conn, objectName ) ) );
534     }
535     
536         public static MBeanAttributeInfo[]
537     filterAttributeInfos(
538         final MBeanAttributeInfo[] infos,
539         final AttributeFilter filter )
540     {
541         final ArrayList JavaDoc<MBeanAttributeInfo> matches = new ArrayList JavaDoc<MBeanAttributeInfo>();
542         for( int i = 0; i < infos.length; ++i )
543         {
544             if ( filter.filterAttribute( infos[ i ] ) )
545             {
546                 matches.add( infos[ i ] );
547             }
548         }
549         
550         final MBeanAttributeInfo[] results = new MBeanAttributeInfo[ matches.size() ];
551         matches.toArray( results );
552         
553         return( results );
554     }
555     
556     /**
557         Get a String[] of Attribute names.
558         
559         @param infos array of infos
560      */

561         public static String JavaDoc []
562     getAttributeNames( final MBeanAttributeInfo[] infos )
563     {
564         final String JavaDoc[] names = new String JavaDoc[ infos.length ];
565         
566         for( int i = 0; i < infos.length; ++i )
567         {
568             names[ i ] = infos[ i ].getName();
569         }
570         
571         return( names );
572     }
573     
574     /**
575         @param infos array of infos
576         @param attrName
577      */

578         public static MBeanAttributeInfo
579     getMBeanAttributeInfo(
580         final MBeanAttributeInfo[] infos,
581         final String JavaDoc attrName )
582     {
583         MBeanAttributeInfo info = null;
584         
585         for( int i = 0; i < infos.length; ++i )
586         {
587             if ( infos[ i ].getName().equals( attrName ) )
588             {
589                 info = infos[ i ];
590                 break;
591             }
592         }
593         
594         return( info );
595     }
596     
597     /**
598         @param mbeanInfo
599         @param attrName
600      */

601         public static MBeanAttributeInfo
602     getMBeanAttributeInfo(
603         final MBeanInfo mbeanInfo,
604         final String JavaDoc attrName )
605     {
606         return( getMBeanAttributeInfo( mbeanInfo.getAttributes(), attrName ) );
607     }
608     
609     
610     /**
611         @param conn
612         @param objectName
613      */

614         public static MBeanAttributeInfo []
615     getAttributeInfos(
616         final MBeanServerConnection conn,
617         final ObjectName objectName )
618         throws IOException JavaDoc,
619             ReflectionException, IntrospectionException, InstanceNotFoundException
620     {
621         final MBeanAttributeInfo [] infos = conn.getMBeanInfo( objectName ).getAttributes();
622         
623         return( infos );
624     }
625     
626     
627     /**
628         Convert an AttributeList to a Map where the keys are the Attribute names,
629         and the values are Attribute.
630         
631         @param attrs the AttributeList
632      */

633         public static Map JavaDoc<String JavaDoc,Attribute>
634     attributeListToAttributeMap( final AttributeList attrs )
635     {
636         final HashMap JavaDoc<String JavaDoc,Attribute> map = new HashMap JavaDoc<String JavaDoc,Attribute>();
637         
638         for( int i = 0; i < attrs.size(); ++i )
639         {
640             final Attribute attr = (Attribute)attrs.get( i );
641             
642             map.put( attr.getName(), attr );
643         }
644         
645         return( map );
646     }
647     
648     /**
649         Convert an AttributeList to a Map where the keys are the Attribute names,
650         and the values are the Attribute values.
651         
652         @param attrs the AttributeList
653      */

654         public static Map JavaDoc<String JavaDoc,Object JavaDoc>
655     attributeListToValueMap( final AttributeList attrs )
656     {
657         final Map JavaDoc<String JavaDoc,Object JavaDoc> map = new HashMap JavaDoc<String JavaDoc,Object JavaDoc>();
658         
659         for( int i = 0; i < attrs.size(); ++i )
660         {
661             final Attribute attr = (Attribute)attrs.get( i );
662             
663             final Object JavaDoc value = attr.getValue();
664             
665             map.put( attr.getName(), value );
666         }
667         
668         return( map );
669     }
670     
671     /**
672         Convert an AttributeList to a Map where the keys are the Attribute names,
673         and the values are the Attribute values.
674         
675         @param attrs the AttributeList
676      */

677         public static Map JavaDoc<String JavaDoc,String JavaDoc>
678     attributeListToStringMap( final AttributeList attrs )
679     {
680         final Map JavaDoc<String JavaDoc,String JavaDoc> map = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
681         
682         for( int i = 0; i < attrs.size(); ++i )
683         {
684             final Attribute attr = (Attribute)attrs.get( i );
685             
686             final Object JavaDoc value = attr.getValue();
687             final String JavaDoc s = (String JavaDoc)(value == null ? value : "" + value);
688             map.put( attr.getName(), s );
689         }
690         
691         return( map );
692     }
693     
694     
695         
696     /**
697         Convert an MBeanAttributeInfo[] to a Map where the keys are the Attribute names,
698         and the values are MBeanAttributeInfo.
699         
700         @param attrInfos the AttributeList
701      */

702         public static Map JavaDoc<String JavaDoc,MBeanAttributeInfo>
703     attributeInfosToMap( final MBeanAttributeInfo[] attrInfos )
704     {
705         final Map JavaDoc<String JavaDoc,MBeanAttributeInfo> map = new HashMap JavaDoc<String JavaDoc,MBeanAttributeInfo>();
706         
707         for( int i = 0; i < attrInfos.length; ++i )
708         {
709             final MBeanAttributeInfo attrInfo = attrInfos[ i ];
710             
711             map.put( attrInfo.getName(), attrInfo );
712         }
713         
714         return( map );
715     }
716     
717     
718         public static MBeanInfo
719     removeAttributes(
720         final MBeanInfo origInfo,
721         final String JavaDoc[] attributeNames )
722     {
723         MBeanInfo result = origInfo;
724         
725         if ( attributeNames.length != 0 )
726         {
727             final Map JavaDoc<String JavaDoc,MBeanAttributeInfo> infos =
728                 JMXUtil.attributeInfosToMap( origInfo.getAttributes() );
729             
730             for( int i = 0; i < attributeNames.length; ++i )
731             {
732                 infos.remove( attributeNames[ i ] );
733             }
734             
735             final MBeanAttributeInfo[] newInfos = new MBeanAttributeInfo[ infos.keySet().size() ];
736             infos.values().toArray( newInfos );
737             
738             result = new MBeanInfo(
739                     origInfo.getClassName(),
740                     origInfo.getDescription(),
741                     newInfos,
742                     origInfo.getConstructors(),
743                     origInfo.getOperations(),
744                     origInfo.getNotifications() );
745         }
746     
747         return( result );
748     }
749     
750     /**
751         Find a feature by name (attribute name, operation name, etc) and return
752         all matches. The feature is matched by calling MBeanFeatureInfo.getName().
753         
754         @param infos infos
755         @param name name
756         @return Set of the matching items
757      */

758         public static Set JavaDoc<MBeanFeatureInfo>
759     findInfoByName(
760         final MBeanFeatureInfo[] infos,
761         final String JavaDoc name )
762     {
763         final Set JavaDoc<MBeanFeatureInfo> s = new HashSet JavaDoc<MBeanFeatureInfo>();
764         
765         for( int i = 0; i < infos.length; ++i )
766         {
767             final MBeanFeatureInfo info = infos[ i ];
768             
769             if ( info.getName().equals( name ) )
770             {
771                 s.add( info );
772             }
773         }
774         
775         return( s );
776     }
777     
778     
779     
780     /**
781         Convert an Map to an Attribute list where the keys are the Attribute names,
782         and the values are objects.
783         
784         @param m
785      */

786         public static AttributeList
787     mapToAttributeList( final Map JavaDoc<String JavaDoc,Object JavaDoc> m )
788     {
789         final AttributeList attrList = new AttributeList();
790         
791         for( final String JavaDoc key : m.keySet() )
792         {
793             final Object JavaDoc value = m.get( key );
794             
795             final Attribute attr = new Attribute( key, value );
796             
797             attrList.add( attr);
798         }
799         
800         return( attrList );
801     }
802     
803     
804     /**
805         Convert ObjectName into a Set of String. The resulting
806         strings are more readable than just a simple toString() on the ObjectName;
807         they are sorted and output in preferential order.
808      */

809         public static List JavaDoc<String JavaDoc>
810     objectNamesToStrings( final Collection JavaDoc<ObjectName> objectNames )
811     {
812         // sorting doesn't work on returned array, so convert to Strings first,then sort
813
final List JavaDoc<String JavaDoc> result = new ArrayList JavaDoc<String JavaDoc>();
814         
815         for( final ObjectName objectName : objectNames )
816         {
817             result.add( ObjectNameStringifier.DEFAULT.stringify( objectName ) );
818         }
819         
820         return( result );
821     }
822     
823     /**
824         Convert a Set of ObjectName into a Set of String
825      */

826         public static String JavaDoc[]
827     objectNamesToStrings( final ObjectName[] objectNames )
828     {
829         final String JavaDoc[] strings = new String JavaDoc[ objectNames.length ];
830         
831         for( int i = 0; i < strings.length; ++i )
832         {
833             strings[ i ] = objectNames[ i ].toString();
834         }
835         
836         return( strings );
837     }
838     
839         private static boolean
840     connectionIsDead( final MBeanServerConnection conn )
841     {
842         boolean isDead = false;
843         
844         // see if the connection is really dead by calling something innocuous
845
try
846         {
847             conn.isRegistered( new ObjectName( MBEAN_SERVER_DELEGATE ) );
848         }
849         catch( MalformedObjectNameException e )
850         {
851             assert( false );
852         }
853         catch( IOException JavaDoc e )
854         {
855             isDead = true;
856         }
857         
858         return( isDead );
859     }
860     
861         private static AttributeList
862     getAttributesSingly(
863         MBeanServerConnection conn,
864         ObjectName objectName,
865         String JavaDoc[] attrNames,
866         Set JavaDoc<String JavaDoc> problemNames )
867         throws InstanceNotFoundException
868     {
869         AttributeList attrs = new AttributeList();
870         
871         for( int i = 0; i < attrNames.length; ++i )
872         {
873             final String JavaDoc name = attrNames[ i ];
874             
875             try
876             {
877                 final Object JavaDoc value = conn.getAttribute( objectName, name );
878                 
879                 attrs.add( new Attribute( name, value ) );
880             }
881             catch( Exception JavaDoc e )
882             {
883                 // if the MBean disappeared while processing, just consider it gone
884
// from the start, even if we got some Attributes
885
if ( e instanceof InstanceNotFoundException )
886                 {
887                     throw (InstanceNotFoundException)e;
888                 }
889                 
890                 if ( problemNames != null )
891                 {
892                     problemNames.add( name );
893                 }
894             }
895         }
896         
897         return( attrs );
898     }
899     
900     
901     /**
902         Get the Attributes using getAttributes() if possible, but if exceptions
903         are encountered, attempt to get them one-by-one.
904         
905         @param conn the conneciton
906         @param objectName name of the object to access
907         @param attrNames attribute names
908         @param problemNames optional Set to which problem names will be added.
909         @return AttributeList
910      */

911         public static AttributeList
912     getAttributesRobust(
913         MBeanServerConnection conn,
914         ObjectName objectName,
915         String JavaDoc[] attrNames,
916         Set JavaDoc<String JavaDoc> problemNames )
917         throws InstanceNotFoundException, IOException JavaDoc
918     {
919         AttributeList attrs = null;
920         
921         if ( problemNames != null )
922         {
923             problemNames.clear();
924         }
925         
926         try
927         {
928             attrs = conn.getAttributes( objectName, attrNames );
929             if ( attrs == null )
930             {
931                 attrs = new AttributeList();
932             }
933         }
934         catch( InstanceNotFoundException e )
935         {
936             // if it's not found, we can't do anything about it.
937
throw e;
938         }
939         catch( IOException JavaDoc e )
940         {
941             if ( connectionIsDead( conn ) )
942             {
943                 throw e;
944             }
945             
946             // connection is still good
947

948             attrs = getAttributesSingly( conn, objectName, attrNames, problemNames );
949         }
950         catch( Exception JavaDoc e )
951         {
952             attrs = getAttributesSingly( conn, objectName, attrNames, problemNames );
953         }
954         
955         return( attrs );
956     }
957     
958     
959     /**
960         Return true if the two MBeanAttributeInfo[] contain the same attributes
961         WARNING: arrays will be sorted to perform the comparison if they are the same length.
962      */

963         boolean
964     sameAttributes( MBeanAttributeInfo[] infos1, MBeanAttributeInfo[] infos2 )
965     {
966         boolean equal = false;
967         
968         if( infos1.length == infos2.length )
969         {
970             equal = ArrayUtil.arraysEqual( infos1, infos2 );
971             if ( ! equal )
972             {
973                 // could still be equal, just in different order
974
Arrays.sort( infos1, MBeanAttributeInfoComparator.INSTANCE );
975                 Arrays.sort( infos2, MBeanAttributeInfoComparator.INSTANCE );
976                 
977                 equal = true; // reset to false upon failure
978
for( int i = 0; i < infos1.length; ++i )
979                 {
980                     if ( ! infos1[ i ].equals( infos2[ i ] ) )
981                     {
982                         equal = false;
983                         break;
984                     }
985                 }
986             }
987             else
988             {
989                 equal = true;
990             }
991         }
992         return( equal );
993     }
994     
995     
996     /**
997         Return true if the two MBeanAttributeInfo[] contain the same operations
998         WARNING: arrays will be sorted to perform the comparison if they are the same length.
999      */

1000        boolean
1001    sameOperations( final MBeanOperationInfo[] infos1, final MBeanOperationInfo[] infos2 )
1002    {
1003        boolean equal = false;
1004        
1005        if ( infos1.length == infos2.length )
1006        {
1007            // if they're in identical order, this is the quickest test if they ultimately succeed
1008
equal = ArrayUtil.arraysEqual( infos1, infos2 );
1009            if ( ! equal )
1010            {
1011                // could still be equal, just in different order
1012
Arrays.sort( infos1, MBeanOperationInfoComparator.INSTANCE );
1013                Arrays.sort( infos2, MBeanOperationInfoComparator.INSTANCE );
1014                
1015                equal = true; // reset to false upon failure
1016
for( int i = 0; i < infos1.length; ++i )
1017                {
1018                    if ( ! infos1[ i ].equals( infos2[ i ] ) )
1019                    {
1020                        equal = false;
1021                        break;
1022                    }
1023                }
1024            }
1025        }
1026        return( equal );
1027    }
1028    
1029    /**
1030        Return true if the MBeanInfos have the same interface (for Attributes and
1031        operations). MBeanInfo.equals() is not sufficient as it will fail if the
1032        infos are in different order, but are actually the same.
1033     */

1034        boolean
1035    sameInterface( MBeanInfo info1, MBeanInfo info2 )
1036    {
1037        return( sameAttributes( info1.getAttributes(), info2.getAttributes() ) &&
1038            sameOperations( info1.getOperations(), info2.getOperations() ) );
1039    }
1040    
1041        public static boolean
1042    isIs( final Method JavaDoc method )
1043    {
1044        return( method.getName().startsWith( IS ) && method.getParameterTypes().length == 0 );
1045    }
1046    
1047    /**
1048        Return true if the method is of the form isXyz() or getXyz()
1049        (no parameters)
1050     */

1051        public static boolean
1052    isGetter( Method JavaDoc method )
1053    {
1054        return( method.getName().startsWith( GET ) && method.getParameterTypes().length == 0 );
1055    }
1056    
1057    
1058        public static boolean
1059    isGetter( final MBeanOperationInfo info )
1060    {
1061        return ( info.getName().startsWith( GET ) &&
1062                info.getSignature().length == 0 &&
1063                ! info.getReturnType().equals( "void" ) );
1064    }
1065
1066
1067        public static MBeanOperationInfo[]
1068    findOperations(
1069        final MBeanOperationInfo[] operations,
1070        final String JavaDoc operationName)
1071    {
1072        final Set JavaDoc<MBeanOperationInfo> items = new HashSet JavaDoc<MBeanOperationInfo>();
1073        for( int i = 0; i < operations.length; ++i )
1074        {
1075            if ( operations[ i ].getName().equals( operationName ) )
1076            {
1077                items.add( operations[ i ] );
1078            }
1079        }
1080        
1081        final MBeanOperationInfo[] itemsArray = new MBeanOperationInfo[ items.size() ];
1082        items.toArray( itemsArray );
1083        return itemsArray;
1084    }
1085    
1086        public static MBeanOperationInfo
1087    findOperation(
1088        final MBeanOperationInfo[] operations,
1089        final String JavaDoc operationName,
1090        final String JavaDoc[] types )
1091    {
1092        MBeanOperationInfo result = null;
1093        
1094        for( int i = 0; i < operations.length; ++i )
1095        {
1096            final MBeanOperationInfo info = operations[ i ];
1097            
1098            if ( info.getName().equals( operationName ) )
1099            {
1100                final MBeanParameterInfo[] sig = info.getSignature();
1101                
1102                if ( sig.length == types.length )
1103                {
1104                    result = info; // assume match...
1105
for( int j = 0; j < sig.length; ++j )
1106                    {
1107                        if ( ! types[ j ].equals( sig[ j ].getType() ) )
1108                        {
1109                            result = null; // no match
1110
break;
1111                        }
1112                    }
1113                }
1114            }
1115        }
1116        
1117        return( result );
1118    }
1119
1120    
1121    /**
1122        Return true if the method is of the form isXyz() or getXyz()
1123        (no parameters)
1124     */

1125        public static boolean
1126    isIsOrGetter( Method JavaDoc method )
1127    {
1128        return( isGetter( method ) || isIs( method ) );
1129    }
1130    
1131        public static String JavaDoc
1132    getAttributeName( final Method JavaDoc method )
1133    {
1134        final String JavaDoc methodName = method.getName();
1135        String JavaDoc attrName = null;
1136        
1137        int prefixLength = 0;
1138        
1139        if ( methodName.startsWith( GET ) || methodName.startsWith( SET ) )
1140        {
1141            prefixLength = 3;
1142        }
1143        else
1144        {
1145            prefixLength = 2;
1146        }
1147        
1148        return( methodName.substring( prefixLength, methodName.length() ) );
1149    }
1150    
1151    
1152        public static boolean
1153    isSetter( Method JavaDoc method )
1154    {
1155        return( method.getName().startsWith( SET ) &&
1156            method.getParameterTypes().length == 1 &&
1157            method.getParameterTypes()[ 0 ] != Attribute.class &&
1158            method.getReturnType().getName().equals( "void" ) );
1159    }
1160    
1161        public static boolean
1162    isGetAttribute( Method JavaDoc m )
1163    {
1164        return( m.getName().equals( "getAttribute" ) &&
1165            m.getParameterTypes().length == 1 && m.getParameterTypes()[ 0 ] == String JavaDoc.class );
1166            
1167    }
1168    
1169        public static boolean
1170    isGetAttributes( Method JavaDoc m )
1171    {
1172        return( m.getName().equals( "getAttributes" ) &&
1173            m.getParameterTypes().length == 1 && m.getParameterTypes()[ 0 ] == String JavaDoc[].class );
1174            
1175    }
1176    
1177        public static boolean
1178    isSetAttribute( Method JavaDoc m )
1179    {
1180        return( m.getName().equals( "setAttribute" ) &&
1181            m.getParameterTypes().length == 1 && m.getParameterTypes()[ 0 ] == Attribute.class );
1182            
1183    }
1184    
1185        public static boolean
1186    isSetAttributes( Method JavaDoc m )
1187    {
1188        return( m.getName().equals( "setAttributes" ) &&
1189            m.getParameterTypes().length == 1 && m.getParameterTypes()[ 0 ] == AttributeList.class );
1190            
1191    }
1192    
1193    
1194        public static ArrayList JavaDoc<MBeanAttributeInfo>
1195    generateAttributeInfos(
1196        final Collection JavaDoc<Method JavaDoc> methodSet,
1197        final boolean read,
1198        final boolean write)
1199    {
1200        final ArrayList JavaDoc<MBeanAttributeInfo> infos = new ArrayList JavaDoc<MBeanAttributeInfo>();
1201        
1202        assert( methodSet != null );
1203    
1204        for( final Method JavaDoc m : methodSet )
1205        {
1206            final String JavaDoc methodName = m.getName();
1207            
1208            assert( read || ( write && methodName.startsWith( SET )) );
1209            final MBeanAttributeInfo info = new MBeanAttributeInfo(
1210                getAttributeName( m ),
1211                m.getReturnType().getName(),
1212                methodName,
1213                read,
1214                write,
1215                methodName.startsWith( "is" )
1216            );
1217            
1218            infos.add( info );
1219        }
1220        
1221        return( infos );
1222    }
1223    
1224        public static MBeanAttributeInfo[]
1225    generateMBeanAttributeInfos(
1226        final Collection JavaDoc<Method JavaDoc> getterSetters,
1227        final Collection JavaDoc<Method JavaDoc> getters,
1228        final Collection JavaDoc<Method JavaDoc> setters )
1229    {
1230        final ArrayList JavaDoc<MBeanAttributeInfo> attrsList = new ArrayList JavaDoc<MBeanAttributeInfo>();
1231        
1232        attrsList.addAll( generateAttributeInfos( getterSetters, true, true ) );
1233        attrsList.addAll( generateAttributeInfos( getters, true, false ) );
1234        attrsList.addAll( generateAttributeInfos( setters, false, true ) );
1235        
1236        final MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[ attrsList.size() ];
1237        attrsList.toArray( attrs );
1238        
1239        return( attrs );
1240    }
1241    
1242    
1243        public static String JavaDoc[]
1244    getSignature( final MBeanParameterInfo[]infos )
1245    {
1246        final String JavaDoc[] sig = new String JavaDoc[ infos.length ];
1247        
1248        int i = 0;
1249        for( final MBeanParameterInfo info : infos )
1250        {
1251            sig[ i ] = info.getType();
1252            ++i;
1253        }
1254        return sig;
1255    }
1256    
1257        public static MBeanParameterInfo[]
1258    generateSignature( final Class JavaDoc[] sig )
1259    {
1260        final MBeanParameterInfo[] infos = new MBeanParameterInfo[ sig.length ];
1261        
1262        for( int i = 0; i < sig.length; ++i )
1263        {
1264            final Class JavaDoc paramClass = sig[ i ];
1265            
1266            final String JavaDoc name = "p" + i;
1267            final String JavaDoc type = paramClass.getName();
1268            final String JavaDoc description = paramClass.getName();
1269            
1270            final MBeanParameterInfo info =
1271                new MBeanParameterInfo( name, type, description );
1272            infos[ i ] = info;
1273        }
1274        
1275        return( infos );
1276    }
1277
1278        public static MBeanOperationInfo[]
1279    generateMBeanOperationInfos(
1280        final Collection JavaDoc<Method JavaDoc> methodSet )
1281    {
1282        final MBeanOperationInfo[] infos = new MBeanOperationInfo[ methodSet.size() ];
1283        
1284        final Iterator JavaDoc iter = methodSet.iterator();
1285    
1286        int i = 0;
1287        while ( iter.hasNext() )
1288        {
1289            final Method JavaDoc m = (Method JavaDoc)iter.next();
1290            final String JavaDoc methodName = m.getName();
1291            
1292            final MBeanOperationInfo info = new MBeanOperationInfo(
1293                methodName,
1294                methodName,
1295                generateSignature( m.getParameterTypes() ),
1296                m.getReturnType().getName(),
1297                MBeanOperationInfo.UNKNOWN
1298            );
1299            
1300            infos[ i ] = info;
1301            ++i;
1302            
1303        }
1304        
1305        return( infos );
1306    }
1307    
1308
1309        public static MBeanInfo
1310    interfaceToMBeanInfo( final Class JavaDoc theInterface )
1311    {
1312        final Method JavaDoc[] methods = theInterface.getMethods();
1313        
1314        final Map JavaDoc<String JavaDoc,Method JavaDoc> getters = new HashMap JavaDoc<String JavaDoc,Method JavaDoc>();
1315        final Map JavaDoc<String JavaDoc,Method JavaDoc> setters = new HashMap JavaDoc<String JavaDoc,Method JavaDoc>();
1316        final Map JavaDoc<String JavaDoc,Method JavaDoc> getterSetters = new HashMap JavaDoc<String JavaDoc,Method JavaDoc>();
1317        final Set JavaDoc<Method JavaDoc> operations = new HashSet JavaDoc<Method JavaDoc>();
1318        
1319        for( int i = 0; i < methods.length; ++i )
1320        {
1321            final Method JavaDoc method = methods[ i ];
1322            
1323            final String JavaDoc methodName = method.getName();
1324            
1325            String JavaDoc attrName = null;
1326            if ( isIsOrGetter( method ) )
1327            {
1328                attrName = getAttributeName( method );
1329                getters.put( attrName, method );
1330            }
1331            else if ( isSetter( method ) )
1332            {
1333                attrName = getAttributeName( method );
1334                setters.put( attrName, method );
1335            }
1336            else
1337            {
1338                operations.add( method );
1339            }
1340            
1341            if ( (attrName != null) &&
1342                    getters.containsKey( attrName ) &&
1343                    setters.containsKey( attrName ) )
1344            {
1345                final Method JavaDoc getter = (Method JavaDoc)getters.get( attrName );
1346                    
1347                final Class JavaDoc getterType = getter.getReturnType();
1348                final Class JavaDoc setterType = ((Method JavaDoc)setters.get( attrName )).getParameterTypes()[ 0 ];
1349                
1350                if ( getterType == setterType )
1351                {
1352                    getters.remove( attrName );
1353                    setters.remove( attrName );
1354                    getterSetters.put( attrName, getter );
1355                }
1356                else
1357                {
1358                    throw new IllegalArgumentException JavaDoc( "Attribute " + attrName +
1359                        "has type " + getterType.getName() + " as getter but type " +
1360                        setterType.getName() + " as setter" );
1361                }
1362            }
1363        }
1364        
1365        /*
1366        java.util.Iterator iter = null;
1367        trace( "-------------------- getterSetters -------------------" );
1368        iter = getterSetters.values().iterator();
1369        while ( iter.hasNext() )
1370        {
1371            trace( ((Method)iter.next()).getName() + ", " );
1372        }
1373        trace( "-------------------- getters -------------------" );
1374        iter = getters.values().iterator();
1375        while ( iter.hasNext() )
1376        {
1377            trace( ((Method)iter.next()).getName() + ", " );
1378        }
1379        trace( "-------------------- setters -------------------" );
1380        iter = setters.values().iterator();
1381        while ( iter.hasNext() )
1382        {
1383            trace( ((Method)iter.next()).getName() + ", " );
1384        }
1385        */

1386        
1387        final MBeanAttributeInfo[] attrInfos =
1388            generateMBeanAttributeInfos( getterSetters.values(),
1389                getters.values(), setters.values() );
1390            
1391        final MBeanOperationInfo[] operationInfos =
1392            generateMBeanOperationInfos( operations );
1393        
1394        final MBeanConstructorInfo[] constructorInfos = null;
1395        final MBeanNotificationInfo[] notificationInfos = null;
1396        
1397        final MBeanInfo mbeanInfo = new MBeanInfo(
1398                theInterface.getName(),
1399                theInterface.getName(),
1400                attrInfos,
1401                constructorInfos,
1402                operationInfos,
1403                notificationInfos );
1404        
1405        return( mbeanInfo );
1406    }
1407    
1408    /**
1409        Merge two MBeanAttributeInfo[]. info1 overrides any duplication in info2.
1410        
1411        @param infos1
1412        @param infos2
1413     */

1414        public static MBeanAttributeInfo[]
1415    mergeMBeanAttributeInfos(
1416        final MBeanAttributeInfo[] infos1,
1417        final MBeanAttributeInfo[] infos2 )
1418    {
1419        // first make a Set of all names in infos1
1420
final Set JavaDoc<String JavaDoc> names = new HashSet JavaDoc<String JavaDoc>();
1421        for( final MBeanAttributeInfo info : infos1 )
1422        {
1423            names.add( info.getName() );
1424        }
1425
1426        final Set JavaDoc<MBeanAttributeInfo> merged = GSetUtil.newSet( infos1 );
1427        
1428        for( final MBeanAttributeInfo info2 : infos2 )
1429        {
1430            final String JavaDoc info2Name = info2.getName();
1431            
1432            if ( ! names.contains( info2Name ) )
1433            {
1434                merged.add( info2 );
1435            }
1436        }
1437
1438        final MBeanAttributeInfo[] infosArray =
1439            new MBeanAttributeInfo[ merged.size() ];
1440        merged.toArray( infosArray );
1441
1442        return( infosArray );
1443    }
1444    
1445    /**
1446        Merge two MBeanNotificationInfo[].
1447        
1448        @param infos1
1449        @param infos2
1450     */

1451        public static MBeanNotificationInfo[]
1452    mergeMBeanNotificationInfos(
1453        final MBeanNotificationInfo[] infos1,
1454        final MBeanNotificationInfo[] infos2 )
1455    {
1456        if ( infos1 == null )
1457        {
1458            return infos2;
1459        }
1460        else if ( infos2 == null )
1461        {
1462            return( infos1 );
1463        }
1464
1465        final Set JavaDoc<MBeanNotificationInfo> all = GSetUtil.newSet( infos1 );
1466        all.addAll( GSetUtil.newSet( infos2 ) );
1467        
1468        final MBeanNotificationInfo[] merged = new MBeanNotificationInfo[ all.size() ];
1469        return all.toArray( merged );
1470    }
1471    
1472    /**
1473        Add MBeanNotificationInfo into the MBeanInfo.
1474        
1475        @param origInfo
1476        @param notifs
1477     */

1478        public static MBeanInfo
1479    addNotificationInfos(
1480        final MBeanInfo origInfo,
1481        final MBeanNotificationInfo[] notifs )
1482    {
1483        MBeanInfo result = origInfo;
1484        
1485        if ( notifs != null && notifs.length != 0 )
1486        {
1487            result = new MBeanInfo(
1488                origInfo.getClassName(),
1489                origInfo.getDescription(),
1490                origInfo.getAttributes(),
1491                origInfo.getConstructors(),
1492                origInfo.getOperations(),
1493                mergeMBeanNotificationInfos( origInfo.getNotifications(), notifs )
1494                );
1495        }
1496        return result;
1497    }
1498
1499    
1500    /**
1501        Merge two MBeanOperationInfo[].
1502        
1503        @param infos1
1504        @param infos2
1505     */

1506        public static MBeanOperationInfo[]
1507    mergeMBeanOperationInfos(
1508        final MBeanOperationInfo[] infos1,
1509        final MBeanOperationInfo[] infos2 )
1510    {
1511        if ( infos1 == null )
1512        {
1513            return infos2;
1514        }
1515        else if ( infos2 == null )
1516        {
1517            return( infos1 );
1518        }
1519        
1520        final Set JavaDoc<MBeanOperationInfo> all = GSetUtil.newSet( infos1 );
1521        all.addAll( GSetUtil.newSet( infos2 ) );
1522        
1523        final MBeanOperationInfo[] merged = new MBeanOperationInfo[ all.size() ];
1524        return all.toArray( merged );
1525    }
1526    
1527    /**
1528        Merge two MBeanOperationInfo[].
1529        
1530        @param infos1
1531        @param infos2
1532     */

1533        public static MBeanConstructorInfo[]
1534    mergeMBeanConstructorInfos(
1535        final MBeanConstructorInfo[] infos1,
1536        final MBeanConstructorInfo[] infos2 )
1537    {
1538        if ( infos1 == null )
1539        {
1540            return infos2;
1541        }
1542        else if ( infos2 == null )
1543        {
1544            return( infos1 );
1545        }
1546        
1547        final Set JavaDoc<MBeanConstructorInfo> all = GSetUtil.newSet( infos1 );
1548        all.addAll( GSetUtil.newSet( infos2 ) );
1549        
1550        final MBeanConstructorInfo[] merged = new MBeanConstructorInfo[ all.size() ];
1551        return all.toArray( merged );
1552    }
1553    
1554    
1555    /**
1556        Merge two MBeanInfo. 'info1' takes priority in conflicts, name, etc.
1557        
1558        @param info1
1559        @param info2
1560     */

1561        public static MBeanInfo
1562    mergeMBeanInfos(
1563        final MBeanInfo info1,
1564        final MBeanInfo info2 )
1565    {
1566        if ( info1 == null )
1567        {
1568            return info2;
1569        }
1570        else if ( info2 == null )
1571        {
1572            return( info1 );
1573        }
1574        
1575        return( new MBeanInfo(
1576            info1.getClassName(),
1577            info1.getDescription(),
1578            mergeMBeanAttributeInfos( info1.getAttributes(), info2.getAttributes() ),
1579            mergeMBeanConstructorInfos( info1.getConstructors(), info2.getConstructors() ),
1580            mergeMBeanOperationInfos( info1.getOperations(), info2.getOperations() ),
1581            mergeMBeanNotificationInfos( info1.getNotifications(), info2.getNotifications() )
1582            ) );
1583            
1584    }
1585    
1586    
1587    /**
1588        Make a new MBeanInfo from an existing one, substituting MBeanAttributeInfo[]
1589        
1590        @param origMBeanInfo
1591        @param newAttrInfos
1592     */

1593        public static MBeanInfo
1594    newMBeanInfo(
1595        final MBeanInfo origMBeanInfo,
1596        final MBeanAttributeInfo[] newAttrInfos )
1597    {
1598        final MBeanInfo info = new MBeanInfo( origMBeanInfo.getClassName(),
1599                                    origMBeanInfo.getDescription(),
1600                                    newAttrInfos,
1601                                    origMBeanInfo.getConstructors(),
1602                                    origMBeanInfo.getOperations(),
1603                                    origMBeanInfo.getNotifications() );
1604        return( info );
1605    }
1606    
1607    /**
1608        Make a new MBeanInfo from an existing one, substituting MBeanOperationInfo[]
1609        
1610        @param origMBeanInfo
1611        @param newOps
1612     */

1613        public static MBeanInfo
1614    newMBeanInfo(
1615        final MBeanInfo origMBeanInfo,
1616        final MBeanOperationInfo[] newOps )
1617    {
1618        final MBeanInfo info = new MBeanInfo( origMBeanInfo.getClassName(),
1619                                    origMBeanInfo.getDescription(),
1620                                    origMBeanInfo.getAttributes(),
1621                                    origMBeanInfo.getConstructors(),
1622                                    newOps,
1623                                    origMBeanInfo.getNotifications() );
1624        return( info );
1625    }
1626    
1627    
1628    /**
1629        Find the index within the MBeanOperationInfo[] of the specified method with the
1630        specified parameter types. If <code>parameterTypes</code> is null, then the
1631        first operation whose name matches is returned.
1632        
1633        @param info
1634        @param methodName
1635        @param parameterTypes
1636        @return the index of the MBeanOperationInfo, or -1 if not found
1637     */

1638        public static int
1639    findMBeanOperationInfo(
1640        final MBeanInfo info,
1641        final String JavaDoc methodName,
1642        final String JavaDoc[] parameterTypes )
1643    {
1644        int resultIdx = -1;
1645        
1646        final MBeanOperationInfo[] ops = info.getOperations();
1647        for( int i = 0; i < ops.length; ++i )
1648        {
1649            final MBeanOperationInfo op = ops[i];
1650            
1651            if ( op.getName().equals( methodName ) &&
1652                    ( parameterTypes == null ||
1653                    ArrayUtil.arraysEqual( parameterTypes, op.getSignature() ) )
1654               )
1655            {
1656                resultIdx = i;
1657                break;
1658            }
1659        }
1660    
1661        return resultIdx;
1662    }
1663    
1664    
1665    
1666        public static boolean
1667    domainMatches(
1668        final String JavaDoc defaultDomain,
1669        final ObjectName pattern,
1670        final ObjectName candidate )
1671    {
1672        boolean matches = false;
1673        
1674        final String JavaDoc candidateDomain = candidate.getDomain();
1675        if ( pattern.isDomainPattern() )
1676        {
1677            final String JavaDoc regex =
1678                RegexUtil.wildcardToJavaRegex( pattern.getDomain() );
1679            
1680            matches = Pattern.matches( regex, candidateDomain);
1681        }
1682        else
1683        {
1684            // domain is not a pattern
1685

1686            String JavaDoc patternDomain = pattern.getDomain();
1687            if ( patternDomain.length() == 0 )
1688            {
1689                patternDomain = defaultDomain;
1690            }
1691            
1692            matches = patternDomain.equals( candidateDomain );
1693        }
1694        
1695        //dm( "MBeanProxyMgrImpl.domainMatches: " + matches + " " + pattern + " vs " + candidate );
1696

1697        return( matches );
1698    }
1699    
1700        public static boolean
1701    matchesPattern(
1702        final String JavaDoc defaultDomain,
1703        final ObjectName pattern,
1704        final ObjectName candidate )
1705    {
1706        boolean matches = false;
1707        
1708        if ( domainMatches( defaultDomain, pattern, candidate ) )
1709        {
1710            final String JavaDoc patternProps = pattern.getCanonicalKeyPropertyListString();
1711            final String JavaDoc candidateProps = candidate.getCanonicalKeyPropertyListString();
1712            assert( patternProps.indexOf( "*" ) < 0 );
1713            assert( candidateProps.indexOf( "*" ) < 0 );
1714            
1715            // Since we used canonical form any match means the pattern props String
1716
// must be a substring of candidateProps
1717
if ( candidateProps.indexOf( patternProps ) >= 0 )
1718            {
1719                matches = true;
1720            }
1721        }
1722        
1723        return( matches );
1724    }
1725    
1726        public static String JavaDoc
1727    toString( final ObjectName objectName )
1728    {
1729        return ObjectNameStringifier.DEFAULT.stringify( objectName );
1730    }
1731    
1732    
1733        public static Notification
1734    cloneNotification(
1735        final Notification in,
1736        final Object JavaDoc source )
1737    {
1738        Notification out = null;
1739        
1740        if ( in.getClass() == AttributeChangeNotification.class )
1741        {
1742            final AttributeChangeNotification a = (AttributeChangeNotification)in;
1743            
1744            out = new AttributeChangeNotification(
1745                source,
1746                a.getSequenceNumber(),
1747                a.getTimeStamp(),
1748                a.getMessage(),
1749                a.getAttributeName(),
1750                a.getAttributeType(),
1751                a.getOldValue(),
1752                a.getNewValue() );
1753        }
1754        else if ( in.getClass() == Notification.class )
1755        {
1756            out = new Notification(
1757                in.getType(),
1758                source,
1759                in.getSequenceNumber(),
1760                in.getTimeStamp(),
1761                in.getMessage() );
1762        }
1763        else
1764        {
1765            throw new IllegalArgumentException JavaDoc( "Not supporting cloning of: " + in.getClass() );
1766        }
1767        
1768        return out;
1769    }
1770    
1771    /**
1772        The sole purpose of this method is to move compiler warnings here, thus
1773        eliminating them from other call sites. May be removed when JMX becomes
1774        generified.
1775     */

1776        public static Set JavaDoc<ObjectName>
1777    queryNames(
1778        final MBeanServerConnection conn,
1779        final ObjectName pattern,
1780        final QueryExp exp)
1781        throws java.io.IOException JavaDoc
1782    {
1783        return TypeCast.asSet( conn.queryNames( pattern, exp ) );
1784    }
1785    
1786    /**
1787        The sole purpose of this method is to move compiler warnings here, thus
1788        eliminating them from other call sites. May be removed when JMX becomes
1789        generified.
1790     */

1791        public static Set JavaDoc<ObjectName>
1792    queryNames(
1793        final MBeanServer server,
1794        final ObjectName pattern,
1795        final QueryExp exp)
1796    {
1797        try
1798        {
1799            return queryNames( (MBeanServerConnection)server, pattern, exp );
1800        }
1801        catch( final IOException JavaDoc e )
1802        {
1803            // ignore, can't happen.
1804
}
1805        return null;
1806    }
1807    
1808    
1809    
1810
1811    /**
1812        Get a Map from the user data field of a Notification.
1813        This variant requires Map<String,Serializable>.
1814     */

1815        public static final <T extends Serializable JavaDoc> Map JavaDoc<String JavaDoc, T>
1816    getUserDataMapString_Serializable( final Notification notif )
1817    {
1818        final Object JavaDoc userData = notif.getUserData();
1819        if ( ! (userData instanceof Map JavaDoc) )
1820        {
1821            throw new IllegalArgumentException JavaDoc();
1822        }
1823        
1824        final Map JavaDoc<String JavaDoc,T> result = TypeCast.asMap( (Map JavaDoc)userData );
1825        if ( result != null )
1826        {
1827            // verify that it's a Map<String,Serializable>
1828
for ( final String JavaDoc testKey : result.keySet() )
1829            {
1830                final T testValue = result.get( testKey );
1831                
1832                result.put( testKey, testValue );
1833            }
1834        }
1835
1836        return result;
1837    }
1838}
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
Popular Tags