KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > cli > jmx > support > CLISupportMBeanImpl


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

23  
24 /*
25  * $Header: /cvs/glassfish/admin-cli/cli-api/src/java/com/sun/cli/jmx/support/CLISupportMBeanImpl.java,v 1.3 2005/12/25 03:45:46 tcfujii Exp $
26  * $Revision: 1.3 $
27  * $Date: 2005/12/25 03:45:46 $
28  */

29  
30
31 package com.sun.cli.jmx.support;
32  
33 import java.lang.reflect.Array JavaDoc;
34 import java.lang.reflect.Constructor JavaDoc;
35 import java.lang.ClassNotFoundException JavaDoc;
36 import java.util.HashSet JavaDoc;
37 import java.util.Set JavaDoc;
38 import java.util.Vector JavaDoc;
39 import java.util.Collections JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.Properties JavaDoc;
43 import java.io.IOException JavaDoc;
44 import javax.management.*;
45
46 import com.sun.cli.util.stringifier.*;
47 import com.sun.cli.util.ClassUtil;
48 import com.sun.cli.util.ArrayConversion;
49 import com.sun.cli.util.ExceptionUtil;
50 import com.sun.cli.jmx.util.ObjectNameQueryImpl;
51
52      
53 interface ClassQuery
54 {
55     public Class JavaDoc getClassForName( String JavaDoc argName )
56         throws ClassNotFoundException JavaDoc;
57 }
58
59
60 final class AttributeClassQuery implements ClassQuery
61 {
62     final MBeanAttributeInfo [] mAttributeInfo;
63     final int mNumInfos;
64     
65         
66     AttributeClassQuery( final MBeanAttributeInfo [] attributeInfo )
67     {
68         mAttributeInfo = attributeInfo;
69         mNumInfos = Array.getLength( attributeInfo );
70     }
71     
72         public Class JavaDoc
73     getClassForName( final String JavaDoc attributeName )
74         throws ClassNotFoundException JavaDoc
75     {
76         Class JavaDoc theClass = Object JavaDoc.class;
77         
78         for( int i = 0; i < mNumInfos; ++i )
79         {
80             final MBeanAttributeInfo info = mAttributeInfo[ i ];
81             
82             if ( attributeName.equals( info.getName() ) )
83             {
84                 theClass = ClassUtil.getClassFromName( info.getType() );
85                 break;
86             }
87         }
88         return( theClass );
89     }
90 }
91
92
93
94
95 final class CLISupportMBeanImpl implements CLISupportMBean
96 {
97     static private final String JavaDoc WILDCARD_PATTERN=",*";
98     static private final String JavaDoc WILDCARD_PATTERN_NOPROPS="*";
99     
100     private final static int WILDCARD_NONE = 0; // "*"
101
private final static int WILDCARD_ALL = 1; // "*"
102
private final static int WILDCARD_READABLE = 2; // "*r"
103
private final static int WILDCARD_WRITEABLE = 3; // "*w"
104

105     private final static char ALIASES_DELIM = ' '; // space
106

107     final MBeanServerConnection mConnection;
108     final AliasMgrMBean mAliasMgr;
109     
110     final ObjectName mAliasMgrName;
111     
112     final ArgParser mParser;
113     
114     
115         private static void
116     p( final Object JavaDoc arg )
117     {
118         System.out.println( arg.toString() );
119     }
120     
121     CLISupportMBeanImpl( final MBeanServerConnection conn, AliasMgrMBean aliasMgr )
122         throws Exception JavaDoc
123     {
124         mConnection = conn;
125         mAliasMgr = aliasMgr;
126         
127         mParser = new ArgParserImpl();
128         
129         mAliasMgrName = new ObjectName( CLISupportStrings.ALIAS_MGR_TARGET );
130     }
131
132         private static final int
133     GetWildcardType( final String JavaDoc s )
134     {
135         int type = WILDCARD_NONE;
136         
137         if ( s.equals( "*" ) )
138             type = WILDCARD_ALL;
139         else if ( s.equals( "*r" ) )
140             type = WILDCARD_READABLE;
141         else if ( s.equals( "*w" ) )
142             type = WILDCARD_WRITEABLE;
143         else
144             type = WILDCARD_NONE;
145         
146         return( type );
147     }
148     
149         private final int
150     GetWildcardType( final String JavaDoc [] strings )
151     {
152         int type = WILDCARD_NONE;
153         
154         final int numItems = Array.getLength( strings );
155
156         for ( int i = 0; i < numItems; ++i )
157         {
158             type = GetWildcardType( strings[ i ] );
159             
160             if ( type != WILDCARD_NONE )
161             {
162                 break;
163             }
164         }
165         return( type );
166     }
167
168
169         static AttributeList
170     ParseAttributes( final String JavaDoc input, final String JavaDoc delim, final ClassQuery classQuery)
171         throws NoSuchMethodException JavaDoc, ClassNotFoundException JavaDoc, ArgParserException
172     {
173         final ArgParser parser = new ArgParserImpl();
174         
175         final ParseResult [] parsedArgs = parser.Parse( input, true );
176         final int numArgs = Array.getLength( parsedArgs );
177         
178         final AttributeList attrList = new AttributeList();
179         
180         for( int i = 0; i < numArgs; ++i )
181         {
182             final ParseResult arg = parsedArgs[ i ];
183             
184             final String JavaDoc argName = arg.getName();
185             
186             try
187             {
188                 final Class JavaDoc theClass = classQuery.getClassForName( argName );
189                 
190                 // theClass will be null if the attribute doesn't exist
191
if ( theClass != null )
192                 {
193                     final ParsedObject parseResult = MatchArg( arg, theClass );
194                     
195                     final Object JavaDoc value = parseResult.mObject;
196                     attrList.add( new Attribute( argName, value ) );
197                 }
198             }
199             catch( Exception JavaDoc e )
200             {
201                 p( "could not parse argument: " + arg );
202             }
203             
204         }
205         
206         return( attrList );
207     }
208
209     
210         private static ParsedObject []
211     ParseArrayAsType( final ParseResult pr, final Class JavaDoc elementType )
212         throws Exception JavaDoc
213     {
214         //p( "ParseArrayAsType: parsing args as " + ClassUtil.getFriendlyClassname( elementType ) );
215

216         final ParseResult [] elems = (ParseResult [])pr.getData();
217         
218         // convert each argument into the appropriate type of object
219
final int numArgs = Array.getLength( elems );
220
221         final ParsedObject [] results = new ParsedObject[ numArgs ];
222         for ( int i = 0; i < numArgs; ++i )
223         {
224             // allow all exceptions to be thrown
225
results[ i ] = MatchArg( elems[ i ], elementType );
226         }
227         
228         return( results );
229     }
230
231
232         private static void
233     checkAssignable( Class JavaDoc requiredClass, Class JavaDoc assignee )
234     {
235         if ( ! requiredClass.isAssignableFrom( assignee ) )
236         {
237             final String JavaDoc str = requiredClass.getName() +
238                                     " is NOT compatible with cast of type " + assignee.getName();
239             //p( str );
240
throw new IllegalArgumentException JavaDoc( str );
241         }
242     }
243     
244         private static void
245     checkIsArray( Class JavaDoc theClass )
246     {
247         if ( ! ClassUtil.classIsArray( theClass ) )
248         {
249             throw new IllegalArgumentException JavaDoc( "does not accept an array" );
250         }
251     }
252     
253         private static Object JavaDoc
254     populatePrimitiveArray( Class JavaDoc primitiveClass, ParsedObject [] parsedData )
255     {
256         final int numItems = Array.getLength( parsedData );
257         Object JavaDoc theArray = Array.newInstance( primitiveClass, numItems );
258         
259         for( int i = 0; i < numItems; ++i )
260         {
261             final Object JavaDoc value = parsedData[ i ].mObject;
262             
263             switch( ClassUtil.getPrimitiveArrayTypeCode( theArray.getClass() ) )
264             {
265                 default: throw new IllegalArgumentException JavaDoc( "not a simple array" );
266                 
267                 case 'Z': Array.setBoolean( theArray, i, ((Boolean JavaDoc)value).booleanValue() ); break;
268                 case 'B': Array.setByte( theArray, i, ((Byte JavaDoc)value).byteValue() ); break;
269                 case 'C': Array.setChar( theArray, i, ((Character JavaDoc)value).charValue() ); break;
270                 case 'S': Array.setShort( theArray, i, ((Short JavaDoc)value).shortValue() ); break;
271                 case 'I': Array.setInt( theArray, i, ((Integer JavaDoc)value).intValue() ); break;
272                 case 'J': Array.setLong( theArray, i, ((Long JavaDoc)value).longValue() ); break;
273                 case 'F': Array.setFloat( theArray, i, ((Float JavaDoc)value).floatValue() ); break;
274                 case 'D': Array.setDouble( theArray, i, ((Double JavaDoc)value).doubleValue() ); break;
275             }
276         }
277         
278         return( theArray );
279     }
280     
281     /*
282         The only checks that need to be here are those that would allow instantiation of the class
283         in spite of invalid values (from CLI point of view). No checks need go here that will fail
284         while the instantiation is being attempted.
285      */

286         private static void
287     CheckValidInstantiation( final Class JavaDoc theClass, String JavaDoc value )
288     {
289         // only allow booleans that are "true" or "false"
290
if ( theClass == Boolean JavaDoc.class || theClass == boolean.class )
291         {
292             if ( ! (value.equalsIgnoreCase( "true" ) || value.equalsIgnoreCase( "false" )) )
293             {
294                 throw new IllegalArgumentException JavaDoc( "not a Boolean/boolean: " + value );
295             }
296         }
297         
298         // for numeric types, out of range checks will fail anyway, so don't bother checking here...
299
}
300         
301         private static boolean
302     isReservedWord_null( String JavaDoc s)
303     {
304         return( s != null && s.equalsIgnoreCase( "null" ) );
305     }
306     
307     /*
308         Parse an argument.
309         
310         @param arg the parsed argument
311         @param requiredClass class specifying required Class of the argument (specify Object if no requirement)
312         
313         @returns an object of the required type, or an exception
314      */

315         static ParsedObject
316     MatchArg( final ParseResult arg, final Class JavaDoc requiredClass )
317         throws Exception JavaDoc
318     {
319         // important: this variable should contain the desired class of the resulting parsed object
320
// It may be *different* than the actual type if logical class is a primitive type, because the parsed
321
// object will be stored as an Object (non-primitive type).
322
Class JavaDoc logicalClass = requiredClass;
323         
324         
325         /* p( "MatchArg: \"" + arg + "\" against class " +
326             ClassUtil.getFriendlyClassname( requiredClass.getName() ) ); */

327         
328         Object JavaDoc resultingObject = null;
329         boolean isNullArg = arg.getData() == null;
330         
331         final int argType = arg.getType();
332         
333         // first check for quoted string
334
if ( argType == ParseResult.LITERAL_STRING )
335         {
336             // extract the quoted string
337
resultingObject = arg.getData();
338             logicalClass = String JavaDoc.class;
339         }
340         else
341         {
342             Class JavaDoc castClass = null;
343             
344             final boolean haveCast = arg.getTypeCast() != null;
345             if ( haveCast )
346             {
347                 //p( "MatchArg: cast = " + arg.getTypeCast() );
348
// extract the class name
349
final String JavaDoc className = ClassUtil.ExpandClassName( arg.getTypeCast() );
350                 castClass = ClassUtil.getClassFromName( className );
351                 
352                 // don't check castClass here for compatibility; it could be an array
353
//p( "MatchArg: castclass = " + arg.getTypeCast() );
354
}
355             assert( (haveCast && castClass != null) || (! haveCast && castClass == null ) );
356             
357             if ( argType == ParseResult.OTHER )
358             {
359                 // not an array, it must be a simple type
360
final String JavaDoc argString = (String JavaDoc)arg.getData();
361                 
362                 if ( haveCast )
363                 {
364                     checkAssignable( requiredClass, castClass );
365                     logicalClass = castClass;
366                 }
367                 
368                 // check for special case of a null object "null" or "NULL".
369
// A cast is significant as it allows selection of a specific signature.
370
if ( isReservedWord_null( argString ) )
371                 {
372                     if ( ClassUtil.IsPrimitiveClass( logicalClass ) )
373                     {
374                         throw new IllegalArgumentException JavaDoc( "primitive class '" +
375                             logicalClass.getName() + "' cannot take a null value" );
376                     }
377                     
378                     resultingObject = null;
379                     isNullArg = true;
380                 }
381                 else
382                 {
383                     if ( ! haveCast )
384                     {
385                         CheckValidInstantiation( logicalClass, argString );
386                     }
387                     
388                     resultingObject = ClassUtil.InstantiateFromString( logicalClass, argString );
389                     //p( "ParseArg: parsed regular object: " + resultingObject.toString() + " as " + logicalClass );
390
}
391             }
392             else if ( argType == ParseResult.ARRAY )
393             {
394                 checkIsArray( requiredClass );
395                 
396                 /*
397                   All arrays have a type for each element. Examples:
398                     type element type inner type
399                     int [] int int
400                     int[][] int[] int
401                     int[][][] int[][] int
402                     
403                     If a cast is present, then the cast means to change the inner element type, so long as it is compatible
404                     with the required type.
405                  */

406                 final Class JavaDoc elementClass = ClassUtil.getArrayElementClass( requiredClass );
407                 final Class JavaDoc innerElementClass = ClassUtil.getInnerArrayElementClass( requiredClass );
408                 
409                 logicalClass = elementClass; // by default, it's as-required
410

411                 /*
412                 p( "element class = " + elementClass.getName() );
413                 p( "inner element class = " + innerElementClass.getName() );
414                 p( "cast class = " + ((castClass == null) ? "null" : castClass.getName()) );
415                 p( "required class = " + requiredClass.getName() );
416                 */

417                 
418                 // If the element type is also an array, alter it's type to reflect the cast.
419
if ( haveCast)
420                 {
421                     checkAssignable( innerElementClass, castClass );
422                     
423                     if ( ClassUtil.classIsArray( elementClass ) )
424                     {
425                         if ( ! ClassUtil.IsPrimitiveClass( innerElementClass ) )
426                         {
427                             logicalClass = ClassUtil.convertArrayClass( elementClass, castClass );
428                         }
429                     }
430                     else
431                     {
432                         logicalClass = castClass;
433                     }
434                 }
435
436                 //p( "MatchArg: array element must be of type " + ClassUtil.getFriendlyClassname( logicalClass ) );
437

438                 final ParsedObject[] parsedData = ParseArrayAsType( arg, logicalClass );
439                 
440                 // convert ParsedObjects into an array of proper type
441
final int numItems = Array.getLength( parsedData );
442                 
443                 if ( ClassUtil.IsPrimitiveClass( logicalClass ) )
444                 {
445                     resultingObject = populatePrimitiveArray( logicalClass, parsedData );
446                 }
447                 else
448                 {
449                     final Object JavaDoc [] realArray =
450                         ArrayConversion.createObjectArrayType( logicalClass, numItems );
451                     for( int i = 0; i < numItems; ++i )
452                     {
453                         realArray[ i ] = parsedData[ i ].mObject;
454                         //p( "elem " + i + " = " + realArray[ i ].getClass().getName() );
455
}
456                     
457                     resultingObject = realArray;
458                 }
459                 logicalClass = resultingObject.getClass();
460             }
461             else
462             {
463                 assert( false );
464             }
465         }
466         
467         assert( (! isNullArg && resultingObject != null) || (isNullArg && resultingObject == null) );
468         
469         checkAssignable( requiredClass, logicalClass );
470         
471         final boolean exactMatch = logicalClass == requiredClass && arg.getTypeCast() != null;
472         
473         final ParsedObject result = new ParsedObject( resultingObject, logicalClass, exactMatch );
474                 
475         return( result );
476     }
477     
478
479
480         private ParseResult []
481     ParseArguments(
482             final String JavaDoc input,
483             final Class JavaDoc requiredType )
484         throws ArgParserException
485     {
486         // it's legal to have no arguments; this is the invocation of an operation with no arguments
487
if ( input == null )
488         {
489             return( new ParseResult [0] );
490         }
491         
492         final ArgParser parser = new ArgParserImpl( );
493         
494         ParseResult [] results = null;
495         
496         /*
497             If it appears to be a named invocation, first try parsing that way.
498             If that fails, just parse as an ordered invocation.
499             The '=' must occur after the first character (or there would be no name).
500             There are other syntactic restrictions of course, but this should eliminate
501             all the cases where no '=' is present (probably 99.9% of the cases).
502             The rest of the time a failed initial parse will detect any other issue.
503          */

504          
505         final boolean possibleNamedInvocation = input.indexOf( "=" ) > 0;
506         if ( possibleNamedInvocation )
507         {
508             try
509             {
510                 results = parser.Parse( input, true );
511             }
512             catch( Exception JavaDoc e )
513             {
514                 // OK, fall through and parse as Ordered invocation
515
}
516         }
517         
518         if ( results == null )
519         {
520             results = parser.Parse( input, false );
521         }
522         
523         return( results );
524     }
525     
526
527     
528     /*
529         Match operation based on all parsedArgs being named and matching names of the operation
530         parameters.
531      */

532         private int
533     GetNamedParamIndex(
534         final String JavaDoc name,
535         final MBeanParameterInfo [] infos)
536     {
537         int paramIndex = -1;
538         
539         final int numParams = Array.getLength( infos );
540         for( int i = 0; i < numParams; ++i )
541         {
542             if ( infos[ i ].getName().equals( name ) )
543             {
544                 paramIndex = i;
545                 break;
546             }
547         }
548         
549         return( paramIndex );
550     }
551     
552     
553     /*
554         Match operation based on all parsedArgs being named and matching names of the operation
555         parameters.
556      */

557         private int
558     MatchNamedOperation(
559         final MBeanOperationInfo info,
560         final ParseResult [] parsedArgs,
561         final ParsedObject [] argsOut )
562     {
563         final int numArgs = Array.getLength( parsedArgs );
564         final MBeanParameterInfo [] paramInfos = info.getSignature();
565         
566         int matchType = MATCH_NONE;
567         
568         final ParseResult [] reorderedResults = new ParseResult [ numArgs ];
569         
570         if ( Array.getLength( paramInfos ) == numArgs )
571         {
572             matchType = MATCH_OK;
573             
574             for( int i = 0; i < numArgs; ++i )
575             {
576                 final String JavaDoc paramName = parsedArgs[ i ].getName();
577
578                 if ( paramName == null || paramName.length() == 0 )
579                 {
580                     matchType = MATCH_NONE;
581                     break;
582                 }
583                 
584                 final int paramIndex = GetNamedParamIndex( paramName, paramInfos );
585                 
586                 if ( paramIndex < 0 )
587                 {
588                     matchType = MATCH_NONE;
589                     break;
590                 }
591                 
592                 reorderedResults[ paramIndex ] = parsedArgs[ i ];
593             }
594             
595             // names have now been used to place the arguments in the proper order.
596
// See if there is a match based on type
597
matchType = MatchOperation( info.getSignature(), reorderedResults, argsOut );
598         }
599         
600         
601         return( matchType );
602     }
603
604
605     private static final int MATCH_NONE = 0;
606     private static final int MATCH_EXACT = 1;
607     private static final int MATCH_OK = 2;
608     
609     /*
610         Match string arguments against possible operation signatures and return the arguments
611         in an ParsedObject [].
612      */

613         private int
614     MatchOperation(
615         final MBeanParameterInfo [] paramInfo,
616         final ParseResult [] parsedArgs,
617         final ParsedObject [] argsOut )
618     {
619         final int numArgs = Array.getLength( parsedArgs );
620         
621         int matchType = MATCH_NONE;
622         
623         if ( paramInfo.length == numArgs )
624         {
625             matchType = MATCH_OK;
626             
627             try
628             {
629                 boolean exactMatch = true;
630                 
631                 for ( int i = 0; i < numArgs; ++i )
632                 {
633                     final String JavaDoc paramClassname = paramInfo[ i ].getType();
634                     final Class JavaDoc paramClass = ClassUtil.getClassFromName( paramClassname );
635                     
636                     //p( "MatchOperation: matching " + ClassUtil.getFriendlyClassname(paramClassname ));
637

638                     argsOut[ i ] = MatchArg( parsedArgs[ i ], paramClass );
639                     argsOut[ i ].mClass = paramClass; // in case it was a primitive class
640

641                     if ( ! argsOut[ i ].mExactMatch )
642                     {
643                         exactMatch = false;
644                     }
645                 }
646                 if ( exactMatch )
647                 {
648                     matchType = MATCH_EXACT;
649                 }
650                 
651             }
652             catch( Exception JavaDoc e )
653             {
654                 matchType = MATCH_NONE;
655             }
656         }
657         
658         if ( matchType != MATCH_NONE )
659         {
660             /* p( "MatchOperation: matched " + AutoStringifier.toString( info ) + " against " +
661                 ArrayStringifier.stringify( parsedArgs, ",", new ParseResultStringifier() ) ); */

662         }
663         
664         return( matchType );
665     }
666     
667     
668     /*
669         Find all matching operations by name.
670         
671         If there are case-sensitive matches, return those,
672         and do not return any case-insensitive matches.
673         
674         Otherwise, return the case-insensitive matches.
675      */

676         private MBeanOperationInfo []
677     GetMatchingMBeanOperationInfo(
678         final String JavaDoc operationName,
679         final MBeanOperationInfo [] operationInfos)
680     {
681         final ArrayList JavaDoc caseSensitiveMatches = new ArrayList JavaDoc();
682         final ArrayList JavaDoc caseInsensitiveMatches = new ArrayList JavaDoc();
683         
684         final int numOps = operationInfos.length;
685         for ( int i = 0; i < numOps; ++i )
686         {
687             final MBeanOperationInfo operationInfo = operationInfos[ i ];
688             final String JavaDoc operationInfoName = operationInfo.getName();
689             
690             if ( operationInfoName.equals( operationName ) )
691             {
692                 caseSensitiveMatches.add( operationInfo );
693             }
694             else if ( operationInfoName.equalsIgnoreCase( operationName ) )
695             {
696                 //p( "GetMatchingMBeanOperationInfo: added: " + operationInfoName + " for " + operationName);
697
caseInsensitiveMatches.add( operationInfo );
698             }
699         }
700         
701         // preferentially return the case-sensitive matches
702
final ArrayList JavaDoc opList = caseSensitiveMatches.size() != 0 ?
703                                     caseSensitiveMatches : caseInsensitiveMatches;
704         
705         return( (MBeanOperationInfo [])opList.toArray( new MBeanOperationInfo [ opList.size() ] ) );
706     }
707     
708     
709         MBeanOperationInfo
710     FindPropertiesOperation( final MBeanOperationInfo [] candidates )
711     {
712         final int numCandidates = Array.getLength( candidates );
713         MBeanOperationInfo info = null;
714         
715         for( int i = 0; i < numCandidates; ++i )
716         {
717             final MBeanParameterInfo [] paramInfos = candidates[ i ].getSignature();
718             
719             if ( paramInfos.length == 1 &&
720                     paramInfos[ 0 ].getType().equals( "java.util.Properties" ) )
721             {
722                 info = candidates[ i ];
723                 break;
724             }
725         }
726         
727         return( info );
728     }
729     
730     
731         private int
732     MatchOperation(
733         final boolean namedInvocation,
734         final MBeanOperationInfo info,
735         final ParseResult [] parsedArgs,
736         final ParsedObject [] argsOut )
737     {
738         int matchType = MATCH_NONE;
739         
740         if ( namedInvocation )
741         {
742             matchType = MatchNamedOperation( info, parsedArgs, argsOut );
743         }
744         else
745         {
746             matchType = MatchOperation( info.getSignature(), parsedArgs, argsOut );
747         }
748         return( matchType );
749     }
750     
751     private static class MatchedOperation
752     {
753         public MBeanOperationInfo mOperationInfo;
754         public ParsedObject [] mArgs;
755         
756             private
757         MatchedOperation( MBeanOperationInfo info, ParsedObject [] args )
758         {
759             mOperationInfo = info;
760             mArgs = args;
761         }
762     }
763
764         private MatchedOperation []
765     MatchOperations(
766         final String JavaDoc requestedOperationName,
767         final boolean namedInvocation,
768         final ParseResult [] parsedArgs,
769         final MBeanOperationInfo [] candidates )
770     {
771         final int numArgs = Array.getLength( parsedArgs );
772         final int numCandidates = Array.getLength( candidates );
773         
774         final ArrayList JavaDoc opList = new ArrayList JavaDoc();
775                 
776         for ( int i = 0; i < numCandidates; ++i )
777         {
778             final ParsedObject [] objectArgs = new ParsedObject [ numArgs ];
779             final MBeanOperationInfo info = candidates[ i ];
780             
781             final int matchType = MatchOperation( namedInvocation, info, parsedArgs, objectArgs );
782             if ( matchType != MATCH_NONE )
783             {
784                 final MatchedOperation matched = new MatchedOperation( info, objectArgs );
785                 
786                 if ( matchType == MATCH_EXACT &&
787                     requestedOperationName.equals( info.getName() ) )
788                 {
789                     //p( "MatchOperations: EXACT MATCH" );
790
opList.clear();
791                     opList.add( matched );
792                     break;
793                 }
794                 else
795                 {
796                     opList.add( matched );
797                     // keep going; could be more than one operation that matches
798
}
799             }
800         }
801             
802         if ( namedInvocation )
803         {
804             if ( opList.size() == 0 )
805             {
806                 // see if there is an operation which takes a java.util.properties
807
final MBeanOperationInfo propertiesOperation = FindPropertiesOperation( candidates );
808                 
809                 if ( propertiesOperation != null )
810                 {
811                     final Properties JavaDoc props = new Properties JavaDoc();
812                     
813                     // add all name/value args to the Properties
814
for( int i = 0; i < numArgs; ++i )
815                     {
816                         final ParseResult arg = parsedArgs[ i ];
817                         props.setProperty( arg.getName(), arg.getData().toString() );
818                     }
819                     
820                     final ParsedObject arg = new ParsedObject( props, Properties JavaDoc.class, false);
821                     final ParsedObject [] args = new ParsedObject [ ] { arg };
822                     
823                     final MatchedOperation matched = new MatchedOperation( propertiesOperation, args );
824                     opList.add( matched );
825                 }
826             }
827         }
828         
829         final MatchedOperation [] matches = new MatchedOperation [ opList.size() ];
830         opList.toArray( matches );
831         
832         return( matches );
833     }
834     
835     
836     private class ParsedObjectArrayStringifier implements Stringifier
837     {
838         final String JavaDoc mOperationName;
839         
840         ParsedObjectArrayStringifier( String JavaDoc operationName )
841         {
842             mOperationName = operationName;
843         }
844         
845         
846              public String JavaDoc
847         stringify( Object JavaDoc o )
848         {
849             final ParsedObject [] signature = (ParsedObject [])o;
850             final String JavaDoc signatureStr = ArrayStringifier.stringify( signature, "," );
851             
852             return( mOperationName + "(" + signatureStr + ")" );
853         }
854     }
855         
856         void
857     throwMultiplePossibleOperationsException( final MatchedOperation [] matches )
858     {
859         // opList is an ArrayList of ParsedObject []
860
final String JavaDoc opStr = ArrayStringifier.DEFAULT.stringify( matches, ",");
861         
862         final String JavaDoc baseStr = "Ambiguous invocation (" + matches.length + " possible operations):\n";
863         throw new IllegalArgumentException JavaDoc( baseStr + opStr +"\n");
864     }
865     
866         private OperationData
867     ParseOperation(
868         final String JavaDoc requestedOperationName,
869         final String JavaDoc argList,
870         final MBeanOperationInfo [] operationInfos )
871         throws Exception JavaDoc
872     {
873         final ParseResult [] parsedArgs = ParseArguments( argList, Object JavaDoc.class );
874         
875         /*p( "\nParseOperation: " +
876             operationName + "(" +
877             ArrayStringifier.stringify( parsedArgs, "|", new ParseResultStringifier( '|')) + ")" );*/

878             
879         
880         // select all the operations with matching names
881
final MBeanOperationInfo [] candidates =
882             GetMatchingMBeanOperationInfo( requestedOperationName, operationInfos );
883         //p( "ParseOperation: num operations with matching name: " + Array.getLength( candidates ) );
884

885         // winnow it down to only those that match
886
final boolean namedInvocation = parsedArgs.length != 0 &&
887                                 parsedArgs[ 0 ].getName() != null;
888                                 
889         final MatchedOperation [] matches = MatchOperations(
890                     requestedOperationName, namedInvocation, parsedArgs, candidates );
891
892
893         // now see if we have exactly one match
894
if ( matches.length != 1 )
895         {
896             if ( matches.length == 0 )
897             {
898                 throw new NoSuchMethodException JavaDoc( "Operation not found: " + requestedOperationName + "()" );
899             }
900             else
901             {
902                 throwMultiplePossibleOperationsException( matches );
903             }
904         }
905
906         final OperationData data =
907                 new OperationData( matches[ 0 ].mOperationInfo.getName(), matches[ 0 ].mArgs );
908             
909         return( data );
910     }
911     
912         private String JavaDoc []
913     GetAttributeNames( final ObjectName objectName, final int wildcardType ) throws Exception JavaDoc
914     {
915         final MBeanInfo allInfo = mConnection.getMBeanInfo( objectName );
916         final MBeanAttributeInfo [] infos = allInfo.getAttributes();
917         
918         final int numAttrs = Array.getLength( infos );
919         final ArrayList JavaDoc results = new ArrayList JavaDoc();
920         for( int i = 0; i < numAttrs; ++i )
921         {
922             final MBeanAttributeInfo info = infos[ i ];
923             final String JavaDoc attributeName = info.getName();
924             
925             final boolean isWriteable = info.isWritable();
926             
927             if ( wildcardType == WILDCARD_READABLE && ! isWriteable )
928             {
929                 results.add( attributeName );
930             }
931             else if ( wildcardType == WILDCARD_WRITEABLE && isWriteable )
932             {
933                 results.add( attributeName );
934             }
935             else if ( wildcardType == WILDCARD_ALL )
936             {
937                 results.add( attributeName );
938             }
939         }
940         
941         return( (String JavaDoc [])results.toArray( new String JavaDoc [ results.size() ] ) );
942     }
943
944
945     /*
946         Supports the mbean-get CLI command
947         
948         @param attrs comma-separated list of attributes
949         @param targets space-separated list of targets
950      */

951          public ResultsForGetSet []
952     mbeanGet( final String JavaDoc attrs, final String JavaDoc [] targets) throws Exception JavaDoc
953     {
954         if ( attrs == null || targets == null )
955         {
956             throw new IllegalArgumentException JavaDoc();
957         }
958
959         final ObjectName [] objects = resolveTargets( targets );
960         
961         String JavaDoc [] attrNames = null;
962         
963         // check first to see if the wildcard "*" has been specified
964
final int wildcardType = GetWildcardType( attrs );
965         if ( wildcardType == WILDCARD_NONE )
966         {
967             attrNames = mParser.ParseNames( attrs );
968         }
969         
970         final int numObjects = Array.getLength( objects );
971         
972         final ResultsForGetSet [] results = new ResultsForGetSet[numObjects ];
973         
974         for ( int objectIndex = 0; objectIndex < numObjects; ++objectIndex )
975         {
976             final ObjectName objectName = objects[ objectIndex ];
977             
978             String JavaDoc [] actualAttrList = null;
979
980             // must refetch for each object as each one could have different attributes; eg the "*"
981
// could resolve to 1 attribute in one object, and 10 in another
982
if ( wildcardType != WILDCARD_NONE )
983             {
984                 actualAttrList = GetAttributeNames( objectName, wildcardType );
985             }
986             else
987             {
988                 actualAttrList = attrNames;
989             }
990             
991             AttributeList idxResults = null;
992             try
993             {
994 /*p( "mbeanGet: getting for: " + objectName.toString() +
995     ", attrs = " + ArrayStringifier.stringify( actualAttrList, ", "));*/

996                 idxResults = mConnection.getAttributes( objectName, actualAttrList );
997             }
998             catch( java.io.IOException JavaDoc e )
999             {
1000                // An IOException is a complete failure; get out
1001
throw e;
1002            }
1003            catch( Exception JavaDoc e )
1004            {
1005                // failure is OK; return empty list as result
1006
idxResults = new AttributeList();
1007            }
1008            
1009            results[ objectIndex ] = new ResultsForGetSet( objectName, idxResults );
1010        }
1011        
1012        return( results );
1013    }
1014    
1015
1016    
1017    /*
1018        Supports the mbean-set CLI command
1019        
1020        @param attrs comma-separated list of attributes/value pairs
1021        @param targets space-separated list of targets
1022     */

1023         public ResultsForGetSet []
1024    mbeanSet( final String JavaDoc attrs, final String JavaDoc [] targets ) throws Exception JavaDoc
1025    {
1026        final ObjectName [] objects = resolveTargets( targets );
1027        
1028        final int numObjects = Array.getLength( objects );
1029        
1030        final ResultsForGetSet [] results = new ResultsForGetSet[numObjects ];
1031        
1032        for ( int objectIndex = 0; objectIndex < numObjects; ++objectIndex )
1033        {
1034            final ObjectName objectName = objects[ objectIndex ];
1035            final MBeanInfo info = mConnection.getMBeanInfo( objectName );
1036            final AttributeClassQuery query = new AttributeClassQuery( info.getAttributes() );
1037            final AttributeList attrList = ParseAttributes( attrs, ",", query);
1038            
1039            AttributeList idxResults = null;
1040            try
1041            {
1042                idxResults = mConnection.setAttributes( objectName, attrList );
1043            }
1044            catch( java.io.IOException JavaDoc e )
1045            {
1046                // An IOException is a complete failure; get out
1047
throw e;
1048            }
1049            catch( Exception JavaDoc e )
1050            {
1051                // failure is OK; return empty list as result
1052
idxResults = new AttributeList();
1053            }
1054            
1055            results[ objectIndex ] = new ResultsForGetSet( objectName, idxResults );
1056        }
1057        
1058        return( results );
1059    }
1060    
1061
1062    /*
1063        We allow omitting the domain prefix and the ":" from an ObjectName.
1064        Supply the domain if not already present.
1065        
1066        This routine's job is to construct a valid ObjectName, not to see if the
1067        MBean actually exists.
1068     */

1069        ObjectName
1070    createObjectName( String JavaDoc target )
1071        throws MalformedObjectNameException
1072    {
1073        ObjectName result = null;
1074        
1075        try
1076        {
1077            // rather than try to interpret it to see if it's an ObjectName, just try it
1078
result = new ObjectName( target );
1079        }
1080        catch( MalformedObjectNameException e )
1081        {
1082            // if no domain was specified, supply "*:" (all domains)
1083
// and supply ",*"
1084
final int colonIndex = target.indexOf( ':' );
1085            if ( colonIndex < 0 )
1086            {
1087                // no domain specified, try with our abbreviation
1088
final String JavaDoc modifiedName = "*:" + target;
1089                
1090                result = convertToPattern( new ObjectName( modifiedName ) );
1091            }
1092            else if ( colonIndex == target.length() -1 )
1093            {
1094                // colon is last character; try adding "*" to the end.
1095
// no domain specified, try with our abbreviation
1096
final String JavaDoc modifiedName = target + "*";
1097                
1098                result = new ObjectName( modifiedName );
1099            }
1100            else
1101            {
1102                // already contains a ":", so assume it's a domain preceeding it
1103
throw e;
1104            }
1105        }
1106        return( result );
1107    }
1108    
1109    /*
1110    
1111            if ( results.size() == 0 )
1112            {
1113                // special hack for S1AS8 which won't show an MBean in a query unless
1114                // GetMBeanInfo is done
1115                try
1116                {
1117                    final MBeanInfo info = mConnection.getMBeanInfo( name );
1118                    // if we got here, there is an MBean with this name
1119                    results.add( name );
1120                }
1121                catch( Exception e )
1122                {
1123                    // ignore
1124                }
1125            }
1126    */

1127    
1128        boolean
1129    exists( final ObjectName name )
1130        throws java.io.IOException JavaDoc
1131    {
1132        return( mConnection.isRegistered( name ) );
1133    }
1134    
1135        ObjectName
1136    convertToPattern( ObjectName input )
1137        throws MalformedObjectNameException
1138    {
1139        ObjectName newName = input;
1140        final String JavaDoc nameString = input.toString();
1141        
1142        if ( ! nameString.endsWith( WILDCARD_PATTERN ) &&
1143            ( ! nameString.endsWith( WILDCARD_PATTERN_NOPROPS ) ) )
1144        {
1145            final String JavaDoc newNameString = nameString + WILDCARD_PATTERN;
1146            
1147            newName = new ObjectName( newNameString );
1148        }
1149        else
1150        {
1151            // already a pattern, and it didn't previously match
1152
}
1153        
1154        return( newName );
1155    }
1156    
1157    /*
1158        Convert an ObjectName to a set of names for MBeans that actually exist.
1159        If the pattern is a fully qualified name,
1160        then the set will consist of a single item (if it exists). If the pattern is a true
1161        pattern, then there may be 1 or more ObjectNames returned.
1162     */

1163         private Set JavaDoc
1164    findObjects( final ObjectName name )
1165        throws MalformedObjectNameException, IOException JavaDoc
1166    {
1167        Set JavaDoc results = Collections.EMPTY_SET;
1168        
1169        if ( name.isPattern())
1170        {
1171            // no choice, we must do a query
1172
results = mConnection.queryNames( name, null );
1173        }
1174        else
1175        {
1176            // it's not a pattern, see if it exists as a fully-qualified name
1177
if ( exists( name ) )
1178            {
1179                results = Collections.singleton( name );
1180            }
1181            else
1182            {
1183                // doesn't exist, interpret it as a pattern
1184
final ObjectName alt = convertToPattern( name );
1185                
1186                if ( ! alt.equals( name ) )
1187                {
1188                    results = mConnection.queryNames( alt, null );
1189                }
1190            }
1191        }
1192        
1193        return( results );
1194    }
1195    
1196 
1197    
1198
1199     /*
1200        Recursively resolve the target into 1 or more ObjectNames.
1201        The 'target' may be an alias, an ObjectName, or an abbreviated ObjectName.
1202        
1203        @param target target to resolve
1204      */

1205        ArrayList JavaDoc
1206     resolveTarget( final String JavaDoc target )
1207        throws MalformedObjectNameException, MBeanException, ReflectionException,
1208        InstanceNotFoundException, IOException JavaDoc
1209     {
1210        final ArrayList JavaDoc objectNames = new ArrayList JavaDoc();
1211        
1212        if ( AliasMgr.isValidAlias( target ) )
1213        {
1214            String JavaDoc value = null;
1215            
1216            try
1217            {
1218                value = resolveAlias( target );
1219            }
1220            catch( Exception JavaDoc e )
1221            {
1222                // squelch
1223
}
1224            
1225            if ( value != null )
1226            {
1227                // could be an alias consisting of other aliases, so split it first
1228
final String JavaDoc [] components = value.split( "" + ALIASES_DELIM );
1229                
1230                final int numComponents = Array.getLength( components );
1231                for( int i = 0; i < numComponents; ++i )
1232                {
1233                    objectNames.addAll( resolveTarget( components[ i ] ) );
1234                }
1235            }
1236        }
1237        else
1238        {
1239            // not an alias, so it must be an ObjectName or pattern
1240
// OR an *abbreviated form* that we allow or a pattern
1241
final ObjectName objectName = createObjectName( target );
1242            final Set JavaDoc nameSet = findObjects( objectName );
1243            objectNames.addAll( nameSet );
1244        }
1245        
1246        
1247        return( objectNames );
1248     }
1249     
1250     /*
1251        Resolve the specified targets, which may be a mix of aliases and/or ObjectNames. An ObjectName in turn
1252        may be abbreviated, fully qualified, or an ObjectName pattern.
1253        
1254        The returned list will not contain any duplicates.
1255        
1256        @param targets array of targets to resolve
1257      */

1258         public ObjectName []
1259     resolveTargets( final String JavaDoc [] targets )
1260        throws MalformedObjectNameException, IOException JavaDoc,
1261            MBeanException, ReflectionException, InstanceNotFoundException
1262     {
1263        final int numTargets = Array.getLength( targets );
1264        
1265        final Set JavaDoc objectNames = new HashSet JavaDoc();
1266            
1267        for( int i = 0; i < numTargets; ++i )
1268        {
1269            String JavaDoc name = targets[ i ];
1270            
1271            final ArrayList JavaDoc values = resolveTarget( name );
1272            objectNames.addAll( values );
1273        }
1274        
1275        // make sure there are no duplicate names
1276
final ObjectName [] objectNamesArray = new ObjectName[ objectNames.size() ];
1277        objectNames.toArray( objectNamesArray );
1278            
1279        return( objectNamesArray );
1280     }
1281
1282    
1283    
1284     
1285    /*
1286        Supports the mbean-invoke CLI command
1287        
1288        @param operationName name of operation to invoke
1289        @param argList comma-separated list of operation arguments
1290        @param targets space-separated list of targets
1291        
1292        @returns array of InvokeResult[], one for each resolved target
1293     */

1294         public InvokeResult []
1295    mbeanInvoke(
1296        final String JavaDoc operationName,
1297        final String JavaDoc argList,
1298        final String JavaDoc [] targets )
1299        throws Exception JavaDoc
1300    {
1301        // p( operationName + "(" + argList + ") on " + SmartStringifier.toString( targets ));
1302

1303        final ObjectName [] objectNames = resolveTargets( targets );
1304
1305        final int numTargets = objectNames.length;
1306        
1307        final InvokeResult results[] = new InvokeResult [ numTargets ];
1308        
1309        for( int i = 0; i < numTargets; ++i )
1310        {
1311            final ObjectName objectName = objectNames[ i ];
1312            final MBeanInfo mbeanInfo = mConnection.getMBeanInfo( objectName );
1313            boolean parsedOK = true;
1314        
1315            OperationData data = null;
1316            results[ i ] = new InvokeResult( objectName, null, null );
1317            
1318            try
1319            {
1320                // parse anew for each object as data types could vary
1321
data = ParseOperation( operationName,
1322                            argList, mbeanInfo.getOperations() );
1323            }
1324            catch( NoSuchMethodException JavaDoc e )
1325            {
1326                // ignore, this object won't be processed
1327
//p( "mbeanInvoke: no such method: " + operationName + "()" );
1328
parsedOK = false;
1329                results[ i ].mThrowable = e;
1330            }
1331            catch( Exception JavaDoc e )
1332            {
1333                /* p( "mbeanInvoke: exception parsing \"" + operationName + "()\"" +
1334                    " object = \"" + objectName.toString() + "\"" ); */

1335                results[ i ].mThrowable = e;
1336                parsedOK = false;
1337            }
1338        
1339            if ( parsedOK )
1340            {
1341                final String JavaDoc [] signature = data.getSignature();
1342                final Object JavaDoc [] args = data.getArgs();
1343                
1344                try
1345                {
1346                    //p( "mbeanInvoke: invoking operation: " + data.mName +
1347
//"(" + ArrayStringifier.stringify( signature, ",", new ClassNameStringifier()) + ")" );
1348

1349                    results[ i ].mResult = mConnection.invoke( objectName, data.mName, args, signature);
1350                }
1351                catch( java.io.IOException JavaDoc e )
1352                {
1353                    // An IOException is a complete failure; get out
1354
throw e;
1355                }
1356                catch( Exception JavaDoc e )
1357                {
1358                    results[ i ].mThrowable = ExceptionUtil.getRootCause( e );
1359                }
1360            }
1361        }
1362        return( results );
1363    }
1364    
1365    /*
1366        Produce a new array of MBeanFeatureInfo containing only items
1367        found in the list of names
1368     */

1369        private Vector JavaDoc
1370    FilterInfoByName( final MBeanFeatureInfo [] info, final String JavaDoc [] names)
1371    {
1372        final int numNames = names.length;
1373        final int numInfo = info.length;
1374        
1375        final Vector JavaDoc filteredInfo = new Vector JavaDoc();
1376        
1377        if ( GetWildcardType( names ) == WILDCARD_ALL )
1378        {
1379            for( int i = 0; i < numInfo; ++i )
1380            {
1381                assert( info[ i ] != null );
1382                filteredInfo.add( info[ i ] );
1383            }
1384        }
1385        else
1386        {
1387            for( int infoIndex = 0; infoIndex < numInfo; ++infoIndex )
1388            {
1389                final MBeanFeatureInfo item = info[ infoIndex ];
1390                
1391                for( int nameIndex = 0; nameIndex < numNames; ++nameIndex )
1392                {
1393                    if ( item.getName().equalsIgnoreCase( names[ nameIndex ] ) )
1394                    {
1395                        filteredInfo.add( item );
1396                        break;
1397                    }
1398                }
1399            }
1400        }
1401        
1402        return( filteredInfo );
1403    }
1404    
1405    
1406
1407    /*
1408        Supports the inspect CLI command
1409        
1410        @param patterns space-separated list of ObjectName patterns
1411     */

1412         public InspectResult
1413    mbeanInspect( final InspectRequest request, final ObjectName name )
1414        throws Exception JavaDoc
1415    {
1416        final MBeanInfo info = mConnection.getMBeanInfo( name );
1417        final ObjectInstance instance = mConnection.getObjectInstance( name );
1418        
1419        final InspectResult result = new InspectResult( instance );
1420        result.includeDescription = request.includeDescription;
1421        
1422        final MBeanAttributeInfo [] attrs = info.getAttributes();
1423        final MBeanOperationInfo [] ops = info.getOperations();
1424        final MBeanConstructorInfo [] constructors = info.getConstructors();
1425        final MBeanNotificationInfo [] notifs = info.getNotifications();
1426        
1427        for( int i = 0; i < ops.length; ++i )
1428        {
1429            assert( ops[ i ] != null ) : "mbeanInspect: MBeanOperationInfo [] has null entries";
1430        }
1431        
1432        String JavaDoc summary = null;
1433        
1434        if ( request.includeSummary )
1435        {
1436            String JavaDoc description = "";
1437            
1438            if ( request.includeDescription )
1439            {
1440                description = "Description: " + info.getDescription() + "\n";
1441            }
1442            
1443            final String JavaDoc nameDelim = "-----";
1444            
1445            summary = description +
1446                        "Class: " + instance.getClassName() + "\n" +
1447                        "Summary: attributes " + Array.getLength( attrs ) +
1448                        ", operations " + Array.getLength( ops ) +
1449                        ", constructors " + Array.getLength( constructors ) +
1450                        ", notifications " + Array.getLength( notifs );
1451        }
1452        result.summary = summary;
1453        
1454        if ( request.attrs != null )
1455        {
1456            final String JavaDoc [] names = mParser.ParseNames( request.attrs );
1457            
1458            final Vector JavaDoc filteredInfo = FilterInfoByName( attrs, names );
1459            
1460            final MBeanAttributeInfo [] results = new MBeanAttributeInfo[ filteredInfo.size() ];
1461            result.attrInfo = (MBeanAttributeInfo [])filteredInfo.toArray( results );
1462        }
1463        
1464        if ( request.operations != null )
1465        {
1466            final String JavaDoc [] names = mParser.ParseNames( request.operations );
1467            
1468            final Vector JavaDoc filteredInfo = FilterInfoByName( ops, names );
1469            
1470            final MBeanOperationInfo [] results = new MBeanOperationInfo[ filteredInfo.size() ];
1471            result.operationsInfo = (MBeanOperationInfo [])filteredInfo.toArray( results );
1472        }
1473        
1474        if ( request.constructors )
1475        {
1476            result.constructorsInfo = constructors;
1477        }
1478        
1479        if ( request.notifications != null )
1480        {
1481            result.notificationsInfo = notifs;
1482        }
1483        
1484        return( result );
1485    }
1486    
1487         public InspectResult []
1488    mbeanInspect( final InspectRequest request, final String JavaDoc [] targets )
1489        throws Exception JavaDoc
1490    {
1491        final ObjectName [] objectNames = resolveTargets( targets );
1492        
1493        final int numObjects = Array.getLength( objectNames );
1494        InspectResult [] results = new InspectResult[ numObjects ];
1495        
1496        for( int i = 0; i < numObjects; ++i )
1497        {
1498            results[ i ] = mbeanInspect( request, objectNames[ i ] );
1499        }
1500        
1501        return( results );
1502    }
1503    
1504    
1505        public ObjectName []
1506    mbeanFind( final String JavaDoc [] patterns )
1507        throws MalformedObjectNameException, IOException JavaDoc, MBeanException,
1508        ReflectionException, InstanceNotFoundException
1509    {
1510        final ObjectName [] names = resolveTargets( patterns );
1511    
1512        return( names );
1513    }
1514    
1515    
1516        public ObjectName []
1517    mbeanFind( final String JavaDoc [] patterns, String JavaDoc regexList )
1518        throws MalformedObjectNameException, IOException JavaDoc, MBeanException,
1519        ReflectionException, InstanceNotFoundException
1520    {
1521        if ( regexList == null )
1522        {
1523            return( mbeanFind( patterns ) );
1524        }
1525        
1526        final ObjectName [] candidates = resolveTargets( patterns );
1527        
1528        
1529        final String JavaDoc [] pairs = regexList.split( "," );
1530        
1531        final String JavaDoc [] regexNames = new String JavaDoc[ pairs.length ];
1532        final String JavaDoc [] regexValues = new String JavaDoc[ pairs.length ];
1533        
1534        for( int i = 0; i < pairs.length; ++i )
1535        {
1536            final String JavaDoc pair = pairs[ i ];
1537            final int delimIndex = pair.indexOf( '=' );
1538            
1539            if ( delimIndex < 0 )
1540            {
1541                throw new IllegalArgumentException JavaDoc( "Malformed regex pair: " + pair );
1542            }
1543            
1544            regexNames[ i ] = pair.substring( 0, delimIndex );
1545            regexValues[ i ] = pair.substring( delimIndex + 1, pair.length() );
1546        }
1547        
1548        final Set JavaDoc startingSet = new HashSet JavaDoc();
1549        startingSet.addAll( java.util.Arrays.asList( candidates ) );
1550        
1551        final ObjectNameQueryImpl query = new ObjectNameQueryImpl();
1552        final Set JavaDoc resultSet = query.matchAll( startingSet, regexNames, regexValues );
1553        
1554        final ObjectName [] results = new ObjectName [ resultSet.size() ];
1555        
1556        resultSet.toArray( results );
1557        
1558        return( results );
1559    }
1560    
1561    
1562        public void
1563    mbeanCreate( String JavaDoc name, String JavaDoc theClass, String JavaDoc argString ) throws Exception JavaDoc
1564    {
1565        final ObjectName objectName = new ObjectName( name );
1566        
1567        if ( argString != null )
1568        {
1569            throw new UnsupportedOperationException JavaDoc( "no support yet for constructors with arguments" );
1570        }
1571        
1572        mConnection.createMBean( theClass, objectName );
1573    }
1574    
1575    
1576    
1577        public void
1578    mbeanUnregister( String JavaDoc name ) throws Exception JavaDoc
1579    {
1580        final ObjectName objectName = new ObjectName( name );
1581        
1582        mConnection.unregisterMBean( objectName );
1583    }
1584    
1585        public int
1586    mbeanCount( ) throws Exception JavaDoc
1587    {
1588        final Integer JavaDoc mbeanCount = mConnection.getMBeanCount( );
1589        
1590        return( mbeanCount.intValue() );
1591    }
1592    
1593        public String JavaDoc []
1594    mbeanDomains( ) throws Exception JavaDoc
1595    {
1596        return( mConnection.getDomains() );
1597    }
1598    
1599    
1600    
1601        public void
1602    mbeanListen(
1603        boolean start,
1604        String JavaDoc [] targets,
1605        NotificationListener listener,
1606        NotificationFilter filter,
1607        Object JavaDoc handback ) throws Exception JavaDoc
1608    {
1609        final ObjectName [] names = resolveTargets( targets );
1610        
1611        for( int i = 0; i < targets.length; ++i )
1612        {
1613            try
1614            {
1615                if ( start )
1616                {
1617                    // if no handback is specified, make it be the ObjectName being listened to
1618
final Object JavaDoc actualHandback = handback == null ? names[ i ] : handback;
1619                    
1620                    mConnection.addNotificationListener( names[ i ], listener, filter,
1621                         actualHandback );
1622                }
1623                else
1624                {
1625                    mConnection.removeNotificationListener( names[ i ], listener );
1626                }
1627            }
1628            catch( java.io.IOException JavaDoc e )
1629            {
1630                // An IOException is a complete failure; get out
1631
throw e;
1632            }
1633            catch( Exception JavaDoc e )
1634            {
1635                p( "Can't listen/stop listening to: " + names[ i ] + " (" + e.getMessage() + ")" );
1636            }
1637        }
1638    }
1639
1640    
1641//-------------- access to AliasMgrMBean ------------------------------
1642

1643
1644    
1645         String JavaDoc
1646    resolveAlias( String JavaDoc aliasName )
1647        throws Exception JavaDoc
1648    {
1649        final String JavaDoc result = mAliasMgr.resolveAlias( aliasName );
1650        return( result );
1651    }
1652    
1653    
1654}
1655
1656
1657
1658
1659
1660
1661
1662
Popular Tags